1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 """Utility functions for manipulating /etc/hosts.
31
32 """
33
34 from cStringIO import StringIO
35
36 from ganeti import pathutils
37
38 from ganeti.utils import algo
39 from ganeti.utils import io
40
41
42 -def SetEtcHostsEntry(file_name, ip, hostname, aliases):
43 """Sets the name of an IP address and hostname in /etc/hosts.
44
45 @type file_name: str
46 @param file_name: path to the file to modify (usually C{/etc/hosts})
47 @type ip: str
48 @param ip: the IP address
49 @type hostname: str
50 @param hostname: the hostname to be added
51 @type aliases: list
52 @param aliases: the list of aliases to add for the hostname
53
54 """
55
56 names = algo.UniqueSequence([hostname] + aliases)
57
58 out = StringIO()
59
60 def _write_entry(written):
61 if not written:
62 out.write("%s\t%s\n" % (ip, " ".join(names)))
63 return True
64
65 written = False
66 for line in io.ReadFile(file_name).splitlines(True):
67 fields = line.split()
68 if fields and not fields[0].startswith("#") and ip == fields[0]:
69 written = _write_entry(written)
70 else:
71 out.write(line)
72 _write_entry(written)
73
74 io.WriteFile(file_name, data=out.getvalue(), uid=0, gid=0, mode=0644,
75 keep_perms=io.KP_IF_EXISTS)
76
77
79 """Wrapper around SetEtcHostsEntry.
80
81 @type hostname: str
82 @param hostname: a hostname that will be resolved and added to
83 L{pathutils.ETC_HOSTS}
84 @type ip: str
85 @param ip: The ip address of the host
86
87 """
88 SetEtcHostsEntry(pathutils.ETC_HOSTS, ip, hostname, [hostname.split(".")[0]])
89
90
91 -def RemoveEtcHostsEntry(file_name, hostname):
92 """Removes a hostname from /etc/hosts.
93
94 IP addresses without names are removed from the file.
95
96 @type file_name: str
97 @param file_name: path to the file to modify (usually C{/etc/hosts})
98 @type hostname: str
99 @param hostname: the hostname to be removed
100
101 """
102 out = StringIO()
103
104 for line in io.ReadFile(file_name).splitlines(True):
105 fields = line.split()
106 if len(fields) > 1 and not fields[0].startswith("#"):
107 names = fields[1:]
108 if hostname in names:
109 while hostname in names:
110 names.remove(hostname)
111 if names:
112 out.write("%s %s\n" % (fields[0], " ".join(names)))
113 continue
114
115 out.write(line)
116
117 io.WriteFile(file_name, data=out.getvalue(), uid=0, gid=0, mode=0644,
118 keep_perms=io.KP_IF_EXISTS)
119
120
132