2013-03-21 91 views
2

我有一个使用AWS SDK(PHP),以更新与友好的主机名以及为每个服务器将当前EC2私有IP的/ etc/hosts文件一个cronjob 。蟒蛇 - 从每行的/ etc/hosts文件得到主机名值

在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 

在Python中,所有我迄今是:

hosts = open('/etc/hosts','r') 
    for line in hosts: 
     print line 

所有我要找的是创造只用主机名的列表(服务器-1,服务器-2等)。有人可以帮我吗?

回答

6
for line in hosts: 
     print line.split()[1:] 
+0

正是我所需要的,谢谢!一旦时间延迟完成,我会接受你的回答,谢谢! – Joe 2013-03-21 21:11:32

1

我知道这个问题是旧的,在技术上解决,但我只是想我会提到,有(现在),将读库(写)hosts文件: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'] 

与上述不同的答案 - 这是公平的是超级简单,做什么要求,不需要任何额外的库 - python-hosts将处理行注释(而不是内嵌的)并有100%的测试覆盖。

0

这应该返回所有的主机名,并应该照顾内嵌评论。

def get_etc_hostnames(): 
    """ 
    Parses /etc/hosts file and returns all the hostnames in a list. 
    """ 
    with open('/etc/hosts', 'r') as f: 
     hostlines = f.readlines() 
    hostlines = [line.strip() for line in hostlines 
       if not line.startswith('#') and line.strip() != ''] 
    hosts = [] 
    for line in hostlines: 
     hostnames = line.split('#')[0].split()[1:] 
     hosts.extend(hostnames) 
    return hosts