我有一个使用 AWS SDK (PHP) 更新/etc/hosts 文件的 cronjob,该文件写入当前 EC2 私有(private) 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 等)的列表。有人可以帮帮我吗?
最佳答案
我知道这个问题很老,技术上已经解决了,但我只是想我会提到(现在)有一个库可以读取(和写入)主机文件: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% 测试覆盖率。
关于python - 从每行/etc/hosts 获取主机名值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558123/