我有一个cronjob,它使用AWS SDK (PHP)来更新/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在Python中,到目前为止我所知道的只有:
hosts = open('/etc/hosts','r')
for line in hosts:
print line我要做的就是创建一个只包含主机名(server-1、server-2等)的列表。有人能帮帮我吗?
发布于 2013-03-22 05:10:32
for line in hosts:
print line.split()[1:]发布于 2017-03-24 18:10:18
我知道这个问题很老,而且在技术上已经解决了,但是我想我应该提一下,(现在)有一个可以读写主机文件的库: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%的测试覆盖率。
发布于 2018-02-22 07:58:21
这应该会返回所有的主机名,并且也应该考虑到内联注释。
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 hostshttps://stackoverflow.com/questions/15558123
复制相似问题