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

Joe picture Joe · Mar 21, 2013 · Viewed 10.7k times · Source

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?

Answer

Mark Ransom picture Mark Ransom · Mar 21, 2013
for line in hosts:
        print line.split()[1:]