Python:加快反向DNS查找
我计划在4700万IP上运行反向DNS。这是我的密码Python:加快反向DNS查找,python,dns,reverse,reverse-dns,Python,Dns,Reverse,Reverse Dns,我计划在4700万IP上运行反向DNS。这是我的密码 with open(file,'r') as f: with open ('./ip_ptr_new.txt','a') as w: for l in f: la = l.rstrip('\n') ip,countdomain = la.split('|') ips.append(ip) try:
with open(file,'r') as f:
with open ('./ip_ptr_new.txt','a') as w:
for l in f:
la = l.rstrip('\n')
ip,countdomain = la.split('|')
ips.append(ip)
try:
ais = socket.gethostbyaddr(ip)
print ("%s|%s|%s" % (ip,ais[0],countdomain), file = w)
except:
print ("%s|%s|%s" % (ip,"None",countdomain), file = w)
目前速度很慢。有人对如何加快速度有什么建议吗?尝试使用多处理模块。我已经为大约8000个IP的性能计时,我得到了以下结果:
#dns.py
real 0m2.864s
user 0m0.788s
sys 0m1.216s
#slowdns.py
real 0m17.841s
user 0m0.712s
sys 0m0.772s
# dns.py
from multiprocessing import Pool
import socket
def dns_lookup(ip):
ip, countdomain = ip
try:
ais = socket.gethostbyaddr(ip)
print ("%s|%s|%s" % (ip,ais[0],countdomain))
except:
print ("%s|%s|%s" % (ip,"None",countdomain))
if __name__ == '__main__':
filename = "input.txt"
ips = []
with open(filename,'r') as f:
with open ('./ip_ptr_new.txt','a') as w:
for l in f:
la = l.rstrip('\n')
ip,countdomain = la.split('|')
ips.append((ip, countdomain))
p = Pool(5)
p.map(dns_lookup, ips)
#slowdns.py
import socket
from multiprocessing import Pool
filename = "input.txt"
if __name__ == '__main__':
ips = []
with open(filename,'r') as f:
with open ('./ip_ptr_new.txt','a') as w:
for l in f:
la = l.rstrip('\n')
ip,countdomain = la.split('|')
ips.append(ip)
try:
ais = socket.gethostbyaddr(ip)
print ("%s|%s|%s" % (ip,ais[0],countdomain), file = w)
except:
print ("%s|%s|%s" % (ip,"None",countdomain), file = w)
这里的一个解决方案是使用带有选项timeout的nslookup shell命令。可能是主机命令。。。 一个不完美但有用的例子
def sh_dns(ip,dns):
a=subprocess.Popen(['timeout','0.2','nslookup','-norec',ip,dns],stdout=subprocess.PIPE)
sortie=a.stdout.read()
tab=str(sortie).split('=')
if(len(tab)>1):
return tab[len(tab)-1].strip(' \\n\'')
else:
return ""
我们最近也不得不处理这个问题。 在多个进程上运行并不能提供足够好的解决方案。 从一台强大的AWS机器上处理数百万个IP可能需要几天的时间。 工作正常的是使用10台集群机器,大约需要半个小时。
您不能用一台机器(通常是一个网络接口)扩展太多,因为这是一项网络密集型任务。在多台机器上使用Map Reduce当然可以做到这一点。运行多个线程/processes@matino我的机器只有两个cpu。而对于python多处理模块2,它的速度不会提高那么多。你能详细说明一下吗?仅仅因为你有两个CPU并不意味着你一次只能运行两个进程。尝试运行更多-这段代码不太可能是CPU受限的。您可以使用两个进程,每个进程生成多个线程,每个线程1)只读取文件的一部分2)因为该部分正在查找host@matino谢谢如果你能把答案分开写,那对我真的很有帮助。谢谢你的帮助。问题是IP的数量很多,要把它们放到一个列表中几乎需要90%的内存。有没有一种方法可以逐行读取数据并将其传递给多处理模块/?很抱歉,我错过了这个要求。在这种情况下,您不能使用列表,而是必须使用队列。从大文件读取仍然可以,因为python使用生成器而不是列表。请检查这条线。嗯,谢谢。但是我仍然不知道在这种情况下如何使用队列好的,我将看看今天是否能够发布一个带有实际代码的编辑。