Python 读取主机名列表并解析为 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34573322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a list of hostnames and resolve to IP addresses
提问by proggynewbie
i'm attempting to read a plain text file and resolve each IP address and (for now) just spit them back out on-screen.
我正在尝试读取纯文本文件并解析每个 IP 地址,并且(目前)只是将它们吐回到屏幕上。
import socket
f = open("test.txt")
num_line = sum(1 for line in f)
f.close()
with open("test.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
for i in range(0,num_line):
x = array[i]
print x
data = socket.gethostbyname_ex(x)
print data
Currently I'm getting the following:
目前我得到以下信息:
me@v:/home/# python resolve-list2.py
test.com
Traceback (most recent call last):
File "resolve-list2.py", line 15, in <module>
data = socket.gethostbyname_ex(x)
socket.gaierror: [Errno -2] Name or service not known
Googling that error doesn't seem to help me... The text file only contains one line at the moment (test.com) but i get the same error even with multiple lines/different hosts.
谷歌搜索该错误似乎对我没有帮助......该文本文件目前仅包含一行(test.com),但即使使用多行/不同主机,我也会收到相同的错误。
Any suggestions?
有什么建议?
Thanks!
谢谢!
采纳答案by YCFlame
import socket
with open("test.txt", "r") as ins:
for line in ins:
print socket.gethostbyname(line.strip())