PageRenderTime 22ms CodeModel.GetById 14ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/silverlining/update_etc_hosts.py

https://bitbucket.org/ianb/silverlining/
Python | 49 lines | 41 code | 0 blank | 8 comment | 1 complexity | 489c9590bed54076443a81e731fdb8f9 MD5 | raw file
 1"""Script to update /etc/hosts
 2
 3This is called by silverlining.etchosts.set_etc_hosts.  It's a separate
 4script because this is called with sudo and runs as root.
 5"""
 6
 7import time
 8
 9
10def update_hosts(filename, ip, hostname):
11    """Add the hostname->ip relation to the given file (typically /etc/hosts)
12    """
13    fp = open(filename)
14    lines = list(fp)
15    fp.close()
16    new_lines = []
17    for line in lines:
18        if not line.strip() or line.strip().startswith('#'):
19            new_lines.append(line)
20            continue
21        line_ip, hostnames = line.strip().split(None, 1)
22        hostnames = hostnames.split()
23        if hostname in hostnames:
24            if line_ip == ip:
25                # Everything is okay... (odd)
26                return
27            # Oh no, we have to kill that!
28            hostnames = hostnames.remove(hostname)
29            if hostnames:
30                new_lines.append('%s %s' % (line_ip, ' '.join(hostnames)))
31            else:
32                if new_lines and new_lines[-1].startswith('# Rackspace'):
33                    new_lines.pop()
34        else:
35            new_lines.append(line)
36    new_lines.append('# Rackspace alias set at %s:\n'
37                     % time.strftime('%c'))
38    new_lines.append('%s %s\n' % (ip, hostname))
39    fp = open(filename, 'w')
40    fp.writelines(new_lines)
41    fp.close()
42
43if __name__ == '__main__':
44    import sys
45    filename = sys.argv[1]
46    ip = sys.argv[2]
47    hostnames = sys.argv[3:]
48    for hostname in hostnames:
49        update_hosts(filename, ip, hostname)