def updateHostsConfigFile(newEntriesList): """ write the latest IP address for the hosts to the system config file """ my_hosts = Hosts() print("Locate the hosts config from : ", my_hosts.determine_hosts_path()) print("Host config entries number : ", my_hosts.count()) #step 1, remove all the entries with the same name for entry in newEntriesList: my_hosts.remove_all_matching(name=entry['Host']) #step 2, add the entry from the new entry list for entry in newEntriesList: new_entry = HostsEntry(entry_type='ipv4', address=entry['Ip'], names=[entry['Host']]) ret = my_hosts.add( [new_entry], allow_address_duplication=True, ) #print(f"Add ipv4 entry for: {new_entry}\n\tOperation result : {ret}\n") #step 3, write the host file result = my_hosts.write() if (result is not None): print("Done! new host file saved! result : \n") print('\n'.join(f'{k} : {v}' for k, v in sorted(result.items()))) else: print("Error! update host file failed! \n")
def prepare_hosts(self): host = self.host_name if host: if self.machine_name: ip = self.machine.ip(machine=self.machine_name) else: ip = '127.0.0.1' self.logger.debug('Prepare hosts: {name} with {ip}'.format(name=host, ip=ip)) hosts = Hosts() for entry in hosts.entries: if entry.address == ip: if host not in entry.names: entry.names.append(host) entry.names = list(set(entry.names)) if not hosts.exists(names=[host]): entry = HostsEntry(entry_type='ipv4', address=ip, names=[host]) hosts.add(entries=[entry]) try: # make backup hosts_path = Hosts.determine_hosts_path() hosts_backup_path = hosts_path + '.' + datetime.datetime.today().strftime('%Y%m%d') shutil.copy(hosts_path, hosts_backup_path) except BaseException: pass try: hosts.write() except BaseException: self.logger.debug('Unable to write host file, ignored.')
def checkoutFromSystem(): tempFile = tempfile.NamedTemporaryFile(delete=False) tempFile.close() hostsPath = Hosts.determine_hosts_path() logger.debug("Checking out '%s' from system to '%s'" % (hostsPath, tempFile.name)) copyfile(hostsPath, tempFile.name) return SubHosts(tempFile.name, tempFile)
def __init__(self, required_aliases: Dict[str, str]): self.required_aliases = required_aliases hosts_path = Hosts.determine_hosts_path() entries_text = tabulate( [(addr, name) for (name, addr) in self.required_aliases.items()], tablefmt="plain") self.suggestions = { OS.GENERIC: f"Add the following entries to {hosts_path}:\n\n{entries_text}" }
def checkHostsLatency(hostname_keyword=None): """ Read host and IP from system hosts config file, Ping the specific host IP to check the average latency in ms """ my_hosts = Hosts() print(my_hosts.determine_hosts_path()) print("Host config entries : ", my_hosts.count()) entry = 0 for host in my_hosts.entries: if (host.entry_type == "ipv4"): if (hostname_keyword is None): # by default print all entries print(host) else: # print entries with keyword hostString = "".join(host.names) hostString = hostString.strip().lower() if (hostname_keyword.strip().lower() in hostString): ipaddr = host.address latency = ping(ipaddr, size=1000, verbose=False).rtt_avg_ms print(entry, f" Latency {latency:<7.2f}ms ", host) entry += 1 if (entry == 0): print(hostname_keyword, " Not found in the host file!\n")
def test_linux_platform_detection(): """ Test that specifying platform 'linux' returns the default linux path to the hosts file """ assert Hosts.determine_hosts_path(platform='linux') == '/etc/hosts'
def test_osx_platform_detection(): """ Test that specifying platform 'darwin' returns the default OSX path to the hosts file """ assert Hosts.determine_hosts_path(platform='darwin') == '/etc/hosts'
def test_windows_platform_detection(): """ Test that specifying platform 'windows' returns the default windows path to the hosts file """ assert Hosts.determine_hosts_path(platform='windows') == r'c:\windows\system32\drivers\etc\hosts'