0

以下代码片段异步获取多个公共 DNS 服务器。如果脚本在 PyCharm 中执行,它可以完美运行,并以非常少的错误解析所有给定的解析器(1078 个请求中约 14 个错误)。

但是,如果我在 OS X 终端中运行完全相同的脚本,则仅首先 ~280 个 aiodns 请求成功,其余返回 aiodns.DNSError(11, 'Could not contact DNS servers')(1078 个请求中的 ~834 个错误)。

从https://pastebin.com/wSYtzebZ复制/粘贴resolvers_short列表

此代码是我在https://github.com/MMquant/DNSweeper/blob/master/DNSweeper.py上的开源项目的一部分

import asyncio
import aiodns

#resolvers_short = [fill resolvers from link]

class Fetcher(object):

    def __init__(self):
        self.loop = asyncio.get_event_loop()

    def get_records(self, names, query_type, resolvers):

        coros = [self._query_sweep_resolvers(names, query_type, resolver) for resolver in resolvers]
        tasks = asyncio.gather(*coros, return_exceptions=True)

        records = self.loop.run_until_complete(tasks)

        return records

    async def _query_sweep_resolvers(self, name, query_type, nameserver):

        resolver = aiodns.DNSResolver(
            nameservers=[nameserver],
            timeout=5,
            tries=3,
            loop=self.loop
        )

        try:
            result = await resolver.query(name, query_type)
        except aiodns.error.DNSError as e:
            result = e

        return {'ns': nameserver,'name': name ,'type': query_type, 'result': result}


def errors_count(results):

    count = 0
    for result in results:
        if type(result['result']) is aiodns.error.DNSError:
            count += 1
    return count


if __name__ == '__main__':

    fetcher = Fetcher()
    results = fetcher.get_records('www.flickr.com', 'A', resolvers_short)
    # print(results)
    errors = errors_count(results)
    # In 1078 resolvers
    # If script executed in PyCharm there are only ~14 aiodns response errors on average
    # If script executed in terminal there are ~834 aiodns response errors where majority are
    # DNSError(11, 'Could not contact DNS servers')
    print(errors)
    pass

我不知道如何继续调试。

这些是我正在使用的模块:

aiodns==1.1.1
pycares==2.3.0
4

1 回答 1

0

我发现 OS X 一次只允许 256 个 TCP 连接。我通过编辑打开文件描述符软限制来增加它

$ ulimit -S -n
256
$ ulimit -S -n 50000
$ ulimit -S -n
50000

我还添加了以下代码以从程序中动态设置打开文件描述符软限制

import resource

new_soft_limit = 50000

(rlimit_nofile_soft, rlimit_nofile_hard) = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft_limit, rlimit_nofile_hard))
于 2018-12-19T17:21:26.507 回答