【问题标题】:How to get the IP address from /etc/hosts?如何从 /etc/hosts 获取 IP 地址?
【发布时间】:2017-01-08 05:48:24
【问题描述】:

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

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

我要做的是,在/etc/hosts 文件中找到gs2 行并获取当前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))

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

【问题讨论】:

    标签: python ubuntu-server


    【解决方案1】:

    使用 .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,则应用不同的分割算法:连续的空格被视为单个分隔符,如果字符串有前导或尾随,结果将在开头或结尾不包含空字符串空白。因此,使用 None 分隔符拆分空字符串或仅包含空格的字符串将返回 []。

    ...

    【讨论】:

    • 更新了我的答案以说明“gs2”并为该字符串提供适当的索引。
    【解决方案2】:

    您的正则表达式正在工作,我认为脚本读取行的方式有点倾斜,因为当我测试时它没有在空格后读取我的行。我最终添加了lines变量。我确信有一种更 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2010-12-21
      相关资源
      最近更新 更多