Revision 9440aeab lib/utils.py
b/lib/utils.py | ||
---|---|---|
752 | 752 |
raise |
753 | 753 |
|
754 | 754 |
|
755 |
def AddEtcHostsEntry(file_name, hostname, ip):
|
|
756 |
"""Adds an IP address and hostname to /etc/hosts.
|
|
755 |
def SetEtcHostsEntry(file_name, ip, hostname, aliases):
|
|
756 |
"""Sets the name of an IP address and hostname in /etc/hosts.
|
|
757 | 757 |
|
758 | 758 |
""" |
759 |
f = open(file_name, 'a+')
|
|
759 |
fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
|
|
760 | 760 |
try: |
761 |
nl = True |
|
762 |
for line in f: |
|
763 |
fields = line.split() |
|
764 |
if len(fields) < 2 or fields[0].startswith('#'): |
|
765 |
continue |
|
766 |
if fields[0] == ip and hostname in fields[1:]: |
|
767 |
break |
|
768 |
nl = line.endswith('\n') |
|
769 |
else: |
|
770 |
if not nl: |
|
771 |
f.write("\n") |
|
772 |
f.write(ip) |
|
773 |
f.write(' ') |
|
774 |
f.write(hostname) |
|
775 |
f.write("\n") |
|
776 |
f.flush() |
|
777 |
finally: |
|
778 |
f.close() |
|
761 |
out = os.fdopen(fd, 'w') |
|
762 |
try: |
|
763 |
f = open(file_name, 'r') |
|
764 |
try: |
|
765 |
written = False |
|
766 |
for line in f: |
|
767 |
fields = line.split() |
|
768 |
if not fields[0].startswith('#') and ip == fields[0]: |
|
769 |
continue |
|
770 |
out.write(line) |
|
771 |
|
|
772 |
out.write("%s %s" % (ip, hostname)) |
|
773 |
if aliases: |
|
774 |
out.write(" %s" % ' '.join(aliases)) |
|
775 |
out.write('\n') |
|
776 |
|
|
777 |
out.flush() |
|
778 |
os.rename(tmpname, file_name) |
|
779 |
finally: |
|
780 |
f.close() |
|
781 |
finally: |
|
782 |
out.close() |
|
783 |
except: |
|
784 |
RemoveFile(tmpname) |
|
785 |
raise |
|
779 | 786 |
|
780 | 787 |
|
781 | 788 |
def RemoveEtcHostsEntry(file_name, hostname): |
782 | 789 |
"""Removes a hostname from /etc/hosts. |
783 | 790 |
|
784 |
IP addresses without hostnames are removed from the file.
|
|
791 |
IP addresses without names are removed from the file. |
|
785 | 792 |
""" |
786 | 793 |
fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name)) |
787 | 794 |
try: |
... | ... | |
797 | 804 |
while hostname in names: |
798 | 805 |
names.remove(hostname) |
799 | 806 |
if names: |
800 |
out.write(fields[0]) |
|
801 |
out.write(' ') |
|
802 |
out.write(' '.join(names)) |
|
807 |
out.write("%s %s\n" % (fields[0], ' '.join(names))) |
|
803 | 808 |
continue |
804 | 809 |
|
805 | 810 |
out.write(line) |
Also available in: Unified diff