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