def fixMaybeLocalhost(hosts_path="/etc/hosts", hostname=None, IP=None): hosts = Hosts(path=hosts_path) removed_hosts = [] # Consider cases where it is added both node.maas and node for h in [hostname.split(".")[0], hostname]: r = hosts.remove_all_matching(name=h) if r: removed_hosts += [str(el) for el in r] hosts.add([HostsEntry(entry_type='ipv4', address=IP, names=[hostname])]) # Check if localhost exists, if not, set it to 127.0.0.1 if len(hosts.find_all_matching(name="localhost")) == 0: # Set localhost hosts.add([ HostsEntry(entry_type='ipv4', address='127.0.0.1', names=["localhost"]) ]) hosts.write() return removed_hosts
def modify_hosts_file_entries(old_name, new_name): """Modify the hosts file to replace old_name with new_name.""" hosts = Hosts() entries = hosts.find_all_matching(name=old_name) # Iterate through all relevant entries for e in entries: # Iterate through all names new_names = [] for n in e.names: # Modify name new_names.append(n.replace(old_name, new_name)) new_entry = HostsEntry(entry_type=e.entry_type, address=e.address, names=new_names, comment=e.comment) # Replace old entry hosts.add([new_entry], force=True) hosts.write()