经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python实现自动化域名批量解析分享
来源:jb51  时间:2022/8/1 13:08:57  对本文有异议

脚本架构:

  • domain_test.py:批量解析运行主程序
  • DomainResult.txt:域名解析结果文件
  • domains.txt:解析的域名文件

实现代码如下:

  1. # coding:utf-8
  2. import socket
  3. import subprocess
  4. import re
  5.  
  6. def get_host_from_file(file_path):
  7. with open(file_path, 'r') as fr:
  8. domains = fr.readlines()
  9. result = []
  10. for url in domains:
  11. url = url.strip()
  12. try:
  13. ips = socket.gethostbyname_ex(url)[-1]
  14. result.append(url + '\t' + ';'.join(ips) + '\t' + 'ping' + '\n')
  15. except Exception as e:
  16. print(url, e)
  17. with open('./domain2ip.txt', 'w') as fw:
  18. fw.writelines(result)
  19.  
  20. def get_host_from_url(url):
  21. try:
  22. ips = socket.gethostbyname_ex(url)[-1]
  23. return url + '\t' + ';'.join(ips) + '\t' + 'ping' + '\n' except Exception as e:
  24. print(url, e)
  25. return url + '\t' + 'none' + '\n'
  26. def dig_test(file_name, dns_name):
  27. dig_command = 'dig ' ip_result = []
  28. if dns_name:
  29. dig_command += dns_name + ' ' with open(file_name) as fr:
  30. domains = fr.readlines()
  31. for ui, full_url in enumerate(domains):
  32. ips = []
  33. full_url = full_url.strip()
  34. try:
  35. result = subprocess.Popen(dig_command + full_url, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  36. except Exception as e:
  37. print(full_url, e)
  38. else:
  39. results = str(result.stdout.read()).split('\\n')
  40. for temp in results:
  41. if full_url in temp and 'IN' in temp:
  42. ip = re.match(r'.*\\t([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*', temp)
  43. if ip and ip.group(1) not in ips:
  44. ips.append(ip.group(1))
  45. if 'AUTHORITY SECTION' in temp:
  46. break if ips:
  47. temp = full_url + '\t' + ';'.join(ips) + '\t' + 'dig' + '\n' else:
  48. temp = get_host_from_url(full_url)
  49. print(ui, temp)
  50. ip_result.append(temp)
  51. #解析完成后,生成结果文件
  52. with open('domains.txt', 'w') as fw:
  53. fw.writelines(ip_result)
  54. if __name__ == '__main__':
  55. # 先使用dig,失败时使用ping获取域名ip,可指定dns,如@114.114.114.114
  56. dig_test(file_name='DomainResults.txt', dns_name='')

演示结果:

到此这篇关于Python实现自动化域名批量解析的文章就介绍到这了,更多相关Python自动化域名解析内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号