批量解析域名为IP地址的python脚本

 

 

脚本如下:

 

#!/usr/bin/env python
#coding:utf-8


import os,sys
from socket import gethostbyname
DOMAIN= "G:/PycharmProject/fullstack2/week1/domain.txt"

def main():
    #domain.txt里面存储的是需要批量解析的域名列表,一行一个
    with open(DOMAIN,'r') as f:
        for line in f.readlines():
            try:
                 host = gethostbyname(line.strip('\n'))
            except Exception as e:
                print e
            else:
                #result.txt里面存储的是批量解析后的结果,不用提前创建
                with open('result.txt','a+') as r:
                    r.write(line.strip('\n') + ' ')
                    r.write(host + '\n')
if __name__ == '__main__':
    main()

这个脚本不完善,因为IP和域名绑定了,但是IP ping不通或者机器关机会出现如下错误

 

[Errno 11001] getaddrinfo failed
[Errno 11001] getaddrinfo failed
[Errno 11001] getaddrinfo failed
[Errno 11001] getaddrinfo failed

 

而且无法确定哪个域名没有和IP绑定

 

 

完善脚本:原创

 

#!/usr/bin/env python
#coding:utf-8


from socket import gethostbyname
DOMAIN= "G:/PycharmProject/fullstack2/week1/e.txt"

with open(DOMAIN,'r') as f:

     for line in f.readlines():
        try:
            host = gethostbyname(line.strip('\n'))  #域名反解析得到的IP
        except Exception as e:
            with open('error.txt','a+') as ERR:  #error.txt为没有IP绑定的域名
                ERR.write(line.strip()+ '\n')
        else:
            with open('result.txt','a+') as r: #result.txt里面存储的是批量解析后的结果
                r.write(line.strip('\n') + ' ')   #显示有ip绑定的域名,用空格隔开
                r.write(host + '\n')

 

 

 

 

参考:

http://www.tiaozhanziwo.com/archives/166.html

 

posted @ 2018-05-07 20:38  钟桂耀  阅读(5568)  评论(0编辑  收藏  举报