我有这个函数来显示域的第一个 IP:
def get_ip_address(url):
command="host "+url
process=os.popen(command)
results=str(process.read())
marker=results.find('has address')+12
print results[marker:].splitlines()[0]
return results[marker:].splitlines()[0]
但这只显示了我的第一个IP。我只想显示 ip。该标记用于没有“有地址”,如下所示(想象我输入“reddit.com”:
['151.101.65.140', 'reddit.com has address 151.101.129.140', 'reddit.com has address 151.101.193.140', 'reddit.com has address 151.101.1.140', 'reddit.com mail is handled by 1 aspmx.l.google.com.', 'reddit.com mail is handled by 10 aspmx2.googlemail.com.', 'reddit.com mail is handled by 10 aspmx3.googlemail.com.', 'reddit.com mail is handled by 5 alt1.aspmx.l.google.com.', 'reddit.com mail is handled by 5 alt2.aspmx.l.google.com.']
我只想显示 ip,而不是 reddit.com 有地址
,也不显示 ip 的末尾、邮件被处理
等。
我尝试过
def get_ip_address(url):
command="host "+url
process=os.popen(command)
results=str(process.read())
marker=results.find('has address')+12
i=0
arrayIps=[]
while "has address" in results[marker:].splitlines()[i]:
print results[marker:].splitlines()[i]
arrayIps.append(results[marker:].splitlines()[i])
print("array")
print arrayIps[i]
i=i+1
return arrayIps
但是它不起作用!甚至没有返回任何有用的东西!
我期待的是一个数组(在本例中):
'151.101.65.140', '151.101.129.140', '151.101.193.140', '151.101.1.140'
最佳答案
看到它根据您的需要显示了多个主机。您的输出可以使用 map
函数生成
In [132]: socket.getaddrinfo("reddit.com", 80, proto=socket.IPPROTO_TCP)
Out[132]:
[(<AddressFamily.AF_INET: 2>,
<SocketKind.SOCK_STREAM: 1>,
6,
'',
('151.101.65.140', 80)),
(<AddressFamily.AF_INET: 2>,
<SocketKind.SOCK_STREAM: 1>,
6,
'',
('151.101.1.140', 80)),
(<AddressFamily.AF_INET: 2>,
<SocketKind.SOCK_STREAM: 1>,
6,
'',
('151.101.129.140', 80)),
(<AddressFamily.AF_INET: 2>,
<SocketKind.SOCK_STREAM: 1>,
6,
'',
('151.101.193.140', 80))]
In [134]: list(map(lambda x:x[4][0],socket.getaddrinfo("reddit.com", 80, proto=socket.IPPROTO_TCP)))
Out[134]: ['151.101.129.140', '151.101.193.140', '151.101.65.140', '151.101.1.140']
关于python - 从python内执行的命令 'host'获取IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53255884/