PageRenderTime 4ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/silverlining/update_etc_hosts.py

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