在python中ping DNS地址列表和返回IP地址

时间:2017-11-06 09:14:55

标签: python-3.x list csv dns ping

提供存储在.csv工作簿中的DNS列表,如何迭代这些DNS列表然后打印一个IP地址列表?以下代码无法正常运行。

import csv


with open('masterlist.csv', 'r') as f:
    reader = csv.reader(f)
your_list = list(reader)
response = os.system("ping -c 1 " + your_list)
print(your_list)

1 个答案:

答案 0 :(得分:0)

假设文件masterlist.csv的内容如下所示:

google.com
stackoverflow.com

这适用于Windows。子进程库是os.system的超集,你应该使用它。

from subprocess import check_output

def get_ip(domain):
    # quick and dirty way of retrieving the ip address, 
    # better use regular expression
    response = check_output(['ping', '-n', '1', domain]).split()[2]
    return response.decode('utf8')

with open('masterlist.csv', 'r') as f:
    ip_addresses = {domain: get_ip(domain) for domain in f.read().splitlines()}

print(ip_addresses)