4

I have a cronjob that uses the AWS SDK (PHP) to update the /etc/hosts file that writes the current EC2 private IP along with a friendly hostname for each server.

In Python, I'm trying to read the /etc/hosts file line by line and just pull out the hostname.

Example /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

In Python, all I have thus far is:

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

All I'm looking for is to create a list with just the hostnames (server-1, server-2, etc). Can someone help me out?

3 Answers 3

9

I know this question is old and technically solved but I just thought I'd mention that there is (now) a library that will read (and write) a hosts file: https://github.com/jonhadfield/python-hosts

The following would result in the same as the accepted answer:

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

Unlike the above answer - which to be fair is super simple, does what's asked and requires no extra libraries - python-hosts will handle line comments (but not inline ones) and has 100% test coverage.

Sign up to request clarification or add additional context in comments.

Comments

7
for line in hosts:
        print line.split()[1:]

1 Comment

exactly what I needed, thanks! will accept your answer once the time delay is done, thanks!
3

This should return all the hostnames and should take care of inline comments too.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.