/silverlining/etchosts.py
Python | 56 lines | 39 code | 4 blank | 13 comment | 17 complexity | af418379b5d5f1a6e2c33f049cb81484 MD5 | raw file
1"""Handle /etc/hosts 2 3This has methods to put a new host->ip setting in /etc/hosts, as well 4as get a setting from that file. 5 6As /etc/hosts can only be edited by root, this ultimately calls out to 7sudo to do the actual edit. 8""" 9 10import os 11from silversupport.shell import run 12 13__all__ = ['set_etc_hosts'] 14 15def set_etc_hosts(config, hostnames, ip): 16 """Sets a line in /etc/hosts to assign the hostname to the ip 17 18 This may add or edit to the file, or do nothing if is already set. 19 It will call a subcommand with sudo if necessary to edit. 20 """ 21 assert not isinstance(hostnames, basestring) 22 fp = open('/etc/hosts') 23 hostnames = set(hostnames) 24 try: 25 for line in fp.read().splitlines(): 26 line = line.strip() 27 if not line.strip() or line.startswith('#'): 28 continue 29 parts = line.split() 30 line_ip = parts[0] 31 line_hosts = parts[1:] 32 if line_ip == ip: 33 for hostname in list(hostnames): 34 if hostname in line_hosts: 35 config.logger.info('Found working ip %s' % line) 36 hostnames.remove(hostname) 37 return 38 force_update = False 39 for hostname in hostnames: 40 if hostname in line_hosts: 41 force_update = True 42 break 43 if force_update: 44 break 45 finally: 46 fp.close() 47 48 cmd = ["sudo", "python", 49 os.path.join(os.path.dirname(__file__), 'update_etc_hosts.py'), 50 "/etc/hosts", 51 ip] + list(hostnames) 52 config.logger.notify('The hostname/ip is not setup in /etc/hosts') 53 resp = config.ask('Would you like me to set it up? ') 54 if resp: 55 config.logger.notify('Executing %s' % ' '.join(cmd)) 56 run(cmd)