如何从/ etc / hosts获取IP地址?

时间:2017-01-08 05:48:25

标签: python ubuntu-server

我的/etc/hosts文件中有以下行

54.230.202.149 gs2.ww.prod.dl.playstation.net

我要做的是,找到gs2文件中的行/etc/hosts并获取当前的IP地址。这就是我所拥有的,但它找不到DNS或返回IP地址。它告诉我,我当前的IP地址是“无”。

try:
     with open('/etc/hosts', 'r') as f:
         for line in f:
             host_ip = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b.+(?=gs2)", line)
             if host_ip:
                 current_ip = host_ip[0].strip()
             else:
                 current_ip = 'None'
except:
    current_ip = 'Unknown'

c.execute('INTERT INTO status VALUES(?,?,?,?,?,?)',
           ('Current Configured IP', current_ip))

不确定问题是什么。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

使用.split()执行此操作,它会将基于空格的行拆分为单独的索引元素。

另请注意,使用此方法不需要host_ip[0].strip(),因为在split()操作期间会删除IP地址和主机名之间的所有空格。您可以使用host_ip[0]

try:
     with open('/etc/hosts', 'r') as f:
         for line in f:
             host_ip = line.split()
             if host_ip and 'gs2' in host_ip[1][0:3]:
                 current_ip = host_ip[0]
             else:
                 current_ip = 'None'
except:
    current_ip = 'Unknown'

来自https://docs.python.org/3/library/stdtypes.html#str.split

(有关split()的进一步讨论,请参阅URL。)

  

str.split(sep = None,maxsplit = -1)

     

...

     

如果未指定sep或为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随,则结果将在开头或结尾处不包含空字符串空白。因此,将空字符串或仅由空格组成的字符串拆分为无分隔符将返回[]。

     

...

答案 1 :(得分:0)

你的正则表达式正在工作,我认为脚本读取线条的方式有点偏斜,因为当我测试它时,在空白后没有读取我的线条。我最后添加了行变量。我确信有更多的pythonic方法来实现这一点,但它的工作原理。

import re

try:
    with open(r'/etc/hosts') as f:
        lines = [line for line in f.read().splitlines() if line]
        for line in lines:
            host_ip = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b.+(?=gs2)", line)
            print(host_ip)
            if host_ip:
                current_ip = host_ip[0].strip()
                print(current_ip)
except:
    current_ip = 'Unknown'
相关问题