share-image
ESC

使用dnspython 模块解析域名

python 的 dnspython 模块,可以用来对域名进行诸如 A 记录、MX 记录、CNAME 记录等解析操作。

安装

python3 安装

pip3 install dnspython3

python2 安装

pip install dnspython

使用

查询A 记录 IP

#!/usr/bin/python3
#-*_coding:utf-8-*-

import dns.resolver


def dnsresolver(domain):

try:
domain = dns.resolver.query(domain,"A")
for domain in domain.response.answer:
for ip in domain.items:
if ip.rdtype == 1:
print("该域名解析的IP地址是:"+ip.address)
else:
pass
except:
print("解析错误:域名参数不正确")


dnsresolver('www.baidu.com')


ß

和dig 查询的A记录地址是一样的

1.查询CNAME

#!/usr/bin/python3
#-*_coding:utf-8-*-

import dns.resolver


def dnsresolver(domain):

try:
domain = dns.resolver.query(domain,"CNAME")
for domain in domain.response.answer:
for ip in domain.items:
#rdtype 为1 表示是A记录
print("该域名解析的IP地址是:"+ip.to_text())
except:
print("解析错误:域名参数不正确")


dnsresolver('fileawenme.b0.aicdn.com')

执行结果

➜  Downloads python3 dnsdemo.py
该域名解析的IP地址是:nm.ctn.aicdn.com.

文章作者:阿文
文章链接: https://www.awen.me/post/54469.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客
本文于 2017-11-02 发布,已超过半年(3010天),请注意甄别内容是否已过期。