2013-03-21 2 views
2

AWS SDK (PHP)를 사용하여 각 서버의 친숙한 호스트 이름과 함께 현재 EC2 개인 IP를 기록하는/etc/hosts 파일을 업데이트하는 cronjob이 있습니다. .python - 각 행의 호스트 이름 값 얻기/etc/hosts

파이썬에서는/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 

, 내가 지금까지 모두입니다 : 내가 찾고 모든 단지 호스트 이름과 목록을 만드는 것입니다

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

(서버 -1, 서버 -2 등). 누군가 나를 도울 수 있습니까?

답변

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

정확하게 감사드립니다! 시간 지연이 완료되면 답변을 수락합니다. – Joe

1

이 질문은 오래되고 기술적으로 해결 알고 있지만 난 그냥 호스트 파일을 (지금)이 있다는 것을 읽을 라이브러리를 언급 (쓰기) 줄 알았는데 다음 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