python - 从python内执行的命令 'host'获取IP

标签 python arrays linux host

我有这个函数来显示域的第一个 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/

相关文章:

python - 使用 ElementTree 读取 .xml 等电子表格

python - Django 导入导出选择字段

ruby 循环重构

linux - 保护 SD 卡 Raspberry Pi 上的数据

linux - 在 Linux 中将文本预先附加到一行

python - tensorflow - 无法从 Anaconda 安装 tensorflow

python - Tensorflow:如何确保每批中的所有样本都有不同的标签?

c - 仅替换用户在 c 中输入的零

javascript - 需要帮助更新 redux reducer 中的操作有效负载数组

c - 我将代码从 FreeBSD 移植到 Linux,但它没有提取目标地址