PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/silverlining/etchosts.py

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