python - get hostname values from each line /etc/hosts

12,584

Solution 1

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

Solution 2

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.

Solution 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
Share:
12,584
Joe
Author by

Joe

Updated on July 16, 2022

Comments

  • Joe
    Joe almost 2 years

    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?

  • Joe
    Joe about 11 years
    exactly what I needed, thanks! will accept your answer once the time delay is done, thanks!