dnspython模块报错 AttributeError: 'CNAME' object has no attribute 'address'

时间:2021-01-02 23:39:52

有时候用到这个模块的时候会报错

AttributeError: 'CNAME' object has no attribute 'address'

如下所示

[root@ansible ch01]# ./dnspython_ex1.py
Please input a domain: www.baidu.com
Traceback (most recent call last):
File "./dnspython_ex1.py", line 9, in <module>
print(j.address)
AttributeError: 'CNAME' object has no attribute 'address'

代码是这样的:

#!/usr/bin/env python
import dns.resolver domain = raw_input('Please input a domain: ')
A = dns.resolver.query(domain, 'A')
for i in A.response.answer:
for j in i.items:
print j.address

我们只需在最后需要输出address时在前面增加if判断

if j.rdtype == 1:

将代码修改如下:

#!/usr/bin/env python
import dns.resolver domain = raw_input('Please input a domain: ')
A = dns.resolver.query(domain, 'A')
for i in A.response.answer:
for j in i.items:
if j.rdtype == 1:
print j.address

运行就不会报错了

[root@ansible ch01]# ./dnspython_ex1.py
Please input a domain: www.baidu.com
14.215.177.38
14.215.177.39