python - 从每行/ etc/hosts获取主机名值

Joe*_*Joe 2 python hosts

我有一个使用AWS开发工具包(PHP)的cronjob来更新/ etc/hosts文件,该文件写入当前的EC2专用IP以及每个服务器的友好主机名.

在Python中,我试图逐行读取/ etc/hosts文件,然后拔出主机名.

示例/ etc/hosts:

127.0.0.1              localhost localhost.localdomain
10.10.10.10            server-1
10.10.10.11            server-2
10.10.10.12            server-3
10.10.10.13            server-4
10.10.10.14            server-5
Run Code Online (Sandbox Code Playgroud)

在Python中,到目前为止我只有:

    hosts = open('/etc/hosts','r')
    for line in hosts:
        print line
Run Code Online (Sandbox Code Playgroud)

我正在寻找的只是创建一个只包含主机名的列表(server-1,server-2等).有人可以帮我吗?

Mar*_*som 6

for line in hosts:
        print line.split()[1:]
Run Code Online (Sandbox Code Playgroud)


otu*_*man 5

我知道这个问题已经很老了并且已经在技术上解决了,但是我只是想提一提,现在有一个可以读取(和写入)主机文件的库:https : //github.com/jonhadfield/python-hosts

以下结果将与接受的答案相同:

from python_hosts import Hosts
[entry.names for entry in hosts.Hosts().entries 
             if entry.entry_type in ['ipv4', 'ipv6']
Run Code Online (Sandbox Code Playgroud)

与上面的答案不同-公平地说,这是非常简单的,所要执行的操作不需要任何额外的库- python-hosts将处理行注释(而不是行内注释)并且具有100%的测试覆盖率。