fix-hosts.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #****************************************************************#
  4. # Create Date: 2017-01-06 17:58
  5. #***************************************************************#
  6. import socket
  7. import shutil
  8. from time import gmtime, strftime
  9. # get host_name
  10. host_name = socket.gethostname()
  11. tmp_file = "/tmp/.lark-fix-host.hosts"
  12. host_file = "/etc/hosts"
  13. bak_file_name = "/tmp/hosts-fix-bak.%s" % ( strftime("%Y-%m-%d_%H-%M-%S", gmtime()) )
  14. # load /etc/hosts file context
  15. FH = open(host_file,"r")
  16. file_lines = [ i.rstrip() for i in FH.readlines()]
  17. FH.close()
  18. file_lines_reverse = file_lines[::-1]
  19. new_lines = []
  20. bad_lines = []
  21. last_match_line = ""
  22. for line in file_lines_reverse:
  23. if line.find(host_name) < 0: # 不匹配的行直接跳过
  24. new_lines.append(line + "\n")
  25. continue
  26. cols = line.split()
  27. new_cols = []
  28. if cols[0].startswith("#"): # 跳过已经注释掉的行
  29. new_lines.append(line + "\n")
  30. continue
  31. for col in cols:
  32. if not col == host_name: # 跳过不匹配的列
  33. new_cols.append(col)
  34. continue
  35. if cols[0] == "127.0.0.1": # 如果第一列是 127.0.0.1 就跳过匹配的列, 防止 hostname -i 返回 127.0.0.1
  36. continue
  37. # 如果已经发现过匹配的列, 就丢掉重复的列
  38. if not len(last_match_line) == 0:
  39. continue
  40. new_cols.append(col)
  41. last_match_line = line
  42. # 跳过 xx.xx.xx.xx hostname 这样的重复列
  43. if len(new_cols) == 1:
  44. continue
  45. new_l = "%s\n" % " ".join(new_cols)
  46. new_lines.append(new_l)
  47. # save tmp hosts
  48. FH2=file(tmp_file,"w+")
  49. FH2.writelines( new_lines[::-1])
  50. FH2.close()
  51. # mv to /etc/hosts
  52. shutil.copy(host_file, bak_file_name)
  53. shutil.move(tmp_file, host_file)