先安装好dnspython
pip install dnspython
脚本正文
# -*- coding: UTF-8 -*-
#!/usr/bin/env python
import sys
from dns import resolver
if len(sys.argv) == 2:
#假如默认查询有报错,走CNAME查询方法
try:
ans = resolver.query(sys.argv[1], "A")
for dns in ans.response.answer:
print(dns)
except BaseException:
ans = resolver.query(sys.argv[1], "CNAME")
for dns in ans.response.answer:
dns = (str(dns))
dnstxt = dns.split(' ')
dnstxt = dnstxt[4:]
ans_res = resolver.query(dnstxt[0], "CNAME")
for result in ans_res.response.answer:
print(result)
else:
pass
elif len(sys.argv) == 3:
#判断是否输入查询关键字为CNAME,非CNAME直接走正常查询流程
try:
ans = resolver.query(sys.argv[1],sys.argv[2])
if sys.argv[2] == "CNAME" or sys.argv[2] == "cname":
for dns in ans.response.answer:
dns = (str(dns))
dnstxt = dns.split(' ')
dnstxt = dnstxt[4:]
ans_res = resolver.query(dnstxt[0], "CNAME")
for result in ans_res.response.answer:
print(result)
else:
for dns in ans.response.answer:
print(dns)
except BaseException:
ans = resolver.query(sys.argv[1], "A")
for dns in ans.response.answer:
print(dns)
else:
pass
else:
print("Example useage: ./dnsQuery.py baidu.com/baidu.com A|CNAME|NS|MX")