def get_remote_hosts(self): ''' parse remote hosts file into python-hosts ''' self.hosts = Hosts(path='/dev/null') self.logger.debug('Cleaning remote hosts..') for line in self.file_handler.hosts: if self.block_start in line: break line_type = HostsEntry.get_entry_type(line) if line_type in ['ipv4', 'ipv6']: self.hosts.add([HostsEntry.str_to_hostentry(line)]) elif line_type == 'comment': self.hosts.add( [HostsEntry(entry_type='comment', comment=line)]) elif line_type == 'blank': # python_hosts.Hosts.add doesn't seem to work for blank lines. # We'll have to use the internal class methods directly. self.hosts.entries.append(HostsEntry(entry_type="blank")) else: self.logger.warning('Unknown line type in hosts file: %s', line) self.hosts.add( [HostsEntry(entry_type='comment', comment=self.block_start)]) if self.params.log_level == logging.DEBUG: self.logger.debug('Cleaned remote hosts:') for entry in self.hosts.entries: print(' ', entry)
def writeHostsFile(self, recv): try: nickname = recv.split(":")[0] address = ipaddress.ip_address(recv.split(":")[1]) packet_id = recv.split(":")[2] timestamp = recv.split(":")[3] ip_type = ipaddress.ip_address(address) self.hosts.remove_all_matching(name=nickname) if isinstance(ip_type, ipaddress.IPv4Address): new_entry = HostsEntry(entry_type='ipv4', address=str(address), names=[nickname]) elif isinstance(ip_type, ipaddress.IPv6Address) and self.ipv6: new_entry = HostsEntry(entry_type='ipv6', address=str(address), names=[nickname]) else: new_entry = HostsEntry(entry_type='blank', address=str(address), names=[nickname]) self.hosts.add([new_entry]) self.hosts.write() except Exception as e: if self.verbose: self.log.error("[LISTENER - writeHostsFile()]: {}".format(e)) else: pass
def init_hosts_file(): hosts = read_hosts() hosts.entries = [] hosts.add([ HostsEntry(entry_type='ipv4', address='127.0.0.1', names=['localhost']), HostsEntry(entry_type='ipv6', address='::1', names=['localhost']), ]) hosts.write()
def add_default_entry(hosts, native=False): if native: hosts.add(entries=[ HostsEntry(entry_type='ipv6', address='::1', names=['localhost6.localdomain6', 'localhost6']) ]) else: hosts.add(entries=[ HostsEntry(entry_type='ipv4', address='127.0.0.1', names=['localhost.localdomain', 'localhost']) ]) return 0
def update_hosts_file(system_config: Config, warning_callback=lambda msg: None): """Update the hosts-file for the current project, if any is loaded and updating is enabled in configuration. The hosts file is written, if it was changed. If it can't be written, warning messages are send to the lambda that outputs how to manually change the host file. :param warning_callback: Callback that receives strings representing warning messages to output to users. :param system_config: System configuration """ if system_config["update_hosts_file"]: if "project" in system_config: hosts = Hosts() new_entries = [] changes = False base_url = system_config["proxy"]["url"] if not hosts.exists(names=[base_url]): changes = True new_entries.append( HostsEntry(entry_type='ipv4', address='127.0.0.1', names=[base_url])) if "services" in system_config["project"]["app"]: for service in system_config["project"]["app"][ "services"].values(): domain = service.domain() if not hosts.exists(names=[domain]): changes = True new_entries.append( HostsEntry(entry_type='ipv4', address='127.0.0.1', names=[domain])) hosts.add(new_entries) if changes: try: hosts.write() except UnableToWriteHosts: entries = "\n".join( [f"{e.address}\t{e.names[0]}" for e in new_entries]) warning_callback( f"Could not update the hosts-file ({hosts.hosts_path}) to configure proxy server routing.\n" f"> Give your user permission to edit this file, to remove this warning.\n" f"> If you wish to manually add the entries instead, " f"add the following entries to {hosts.hosts_path}:\n{entries}\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 add_hosts(self, hostnames, do_write=True): ''' create HostsEntry for a host and add it to Hosts object, optionally write out ''' parsed_hostnames = self.parse_hostnames(hostnames) parsed_items = parsed_hostnames.items() if parsed_items: for host_ip, names in parsed_items: self.logger.debug('Adding: (%s) %s', host_ip, names) hostentry = HostsEntry(entry_type='ipv4', address=host_ip, names=names) self.hosts.add([hostentry], force=True, allow_address_duplication=True) if do_write: self.queue_write() self.logger.info('Added host(s): %s', sum(parsed_hostnames.values(), [])) else: self.logger.info('Host already exists, nothing to add.') return parsed_items
def set_hostname(): macaddress = NetInfo.get_default_mac().replace(":", "") default_hostname = "pi-" + macaddress init_hostname = socket.gethostname() logger.debug("get hostname = %s" % init_hostname) # self.hostname = inithostname if init_hostname != default_hostname: logger.debug("set hostname = %s" % init_hostname) # 重设主机名 args = "hostname %s " % default_hostname subprocess.Popen(args, shell=True, stdout=subprocess.PIPE).communicate() # 修改/etc/hostname文件 f = open('/etc/hostname', 'w') f.write(default_hostname) f.close() # 修改/etc/hosts if 'linux' in sys.platform or 'darwin' in sys.platform: filename = '/etc/hosts' else: filename = 'c:\windows\system32\drivers\etc\hosts' hosts = Hosts(path=filename) # 移除旧域名 hosts.remove_all_matching(name=init_hostname) new_entry = HostsEntry(entry_type='ipv4', address='127.0.0.1', names=[default_hostname]) hosts.add([new_entry]) hosts.write()
def addEntry(self, name, destAddress): self.removeEntry(name) entry = HostsEntry(entry_type='ipv4', address=destAddress, names=[name]) self.add([entry], True) return entry
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 add_entry(self, ip, name): name = name + ".dev" # just to be safe self.remove_entry(ip, name) new_entry = HostsEntry(entry_type='ipv4', address=ip, names=[name]) self.my_hosts.add([new_entry]) self.my_hosts.write()
def _write_hosts_file(self, overrides): hosts_file = Hosts(path='/etc/hosts') hosts_file.add([ HostsEntry(entry_type='ipv4', address=override.ip_address, names=[override.hostname]) for override in overrides ]) hosts_file.write()
def set_hosts(address, names, type='ipv4'): '''add item to system hosts file''' from python_hosts import Hosts, HostsEntry hosts = Hosts() if isinstance(names, str): names = [names] new_entry = HostsEntry(entry_type=type, address=address, names=names) hosts.add([new_entry]) hosts.write()
def add_address_to_host(address, *hosts): for host in hosts: remove_host_if_exists(host) hosts_in_file = read_hosts() if not hosts_in_file.entries: init_hosts_file() hosts_in_file = read_hosts() hosts_in_file.add( [HostsEntry(entry_type='ipv4', address=address, names=list(hosts))]) hosts_in_file.write()
def modify_etc_hosts(data): private_ip = data['private_ip'] hostname = socket.gethostname() hosts = Hosts() new_entry = HostsEntry(entry_type='ipv4', address=private_ip, names=[hostname]) hosts.add([new_entry]) hosts.write()
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 add_host(self, fqdn, ip_addr, entry_type='ipv4'): ''' add a host by fqdn and ip address ''' with self.lock.acquire(timeout=5): self.hostfile = Hosts(self.hosts_file_path) LOGGER.info("Adding entry for %s at %s", fqdn, ip_addr) new_entry = HostsEntry(entry_type=entry_type, address=ip_addr, names=[fqdn]) self.hostmap[fqdn] = True self.hostfile.add([new_entry], True) self._write_hosts_file()
def add_host(): """ Add hosts entry for the server IP """ hosts = Hosts() hosts.add([ HostsEntry( entry_type='ipv4', address=GCEMetadata.IP, names=GCEMetadata.HOSTS, ), ]) hosts.write()
def update_all_hosts(hosts_list): hosts = Hosts('/home/xin/hosts') entries = [] for row in hosts_list: entry = HostsEntry(entry_type=row.get('ip_type', 'ipv4'), address=row["ip"], names=[row['hostname']]) entries.append(entry) ret = hosts.add(entries, force=True, merge_names=True) hosts.write() return ret
def _gen_entries(): for network_name, network_address in current_config.get( 'networks', {}).items(): name = _fmt(name=current_config['name'], hostname=current_config['hostname'], network=network_name) if network_address and network_name: logger.debug("Adding host entry %s <> %s", network_address, name) yield HostsEntry(entry_type='ipv4', address=network_address, names=[name])
def main(): hosts = Hosts(path='/etc/hosts') layout = json.load(open(LAYOUT_JSON)) for name, config in layout.get('groups', {}).items(): for host, ip in config.get('ips', {}).items(): host = host.lower() hosts.remove_all_matching(name=host) new_entry = HostsEntry(entry_type='ipv4', address=ip, names=[host]) hosts.add([new_entry]) hosts.write()
def update_hosts_file(address,hostname,profile): if profile is not None: copyfile("/etc/hosts", "hosts") etchostname = profile.replace(" ", "_") + ("-" + hostname if hostname else "") print(f"Updating hostname as: {etchostname} with {address}") hosts = Hosts(path='hosts') hosts.remove_all_matching(name=etchostname) new_entry = HostsEntry(entry_type='ipv4', address=address, names=[etchostname]) hosts.add([new_entry]) hosts.write() copyfile("hosts", "/etc/hosts") print(f"Updated Host name for hostsfile is {etchostname}")
def edit_host(enable): hosts = Hosts() if enable: entry = HostsEntry(entry_type='ipv4', address='127.0.0.1', names=[ 'us-or-rly101.zwift.com', 'secure.zwift.com', 'cdn.zwift.com', 'launcher.zwift.com' ]) hosts.add([entry]) else: hosts.remove_all_matching(name='cdn.zwift.com') logger.info(hosts.write())
def main(self): i = 0 while self.isrunning: hosts = Hosts(path='C:\Windows\System32\drivers\etc\hosts') r = requests.get('http://dev.nsyncdata.net:9000/hosts') r = r.json() for item in r['Remove']: hosts.remove_all_matching(name=item['URL']) for item in r['Add']: new = HostsEntry(entry_type='ipv4', address=item['Address'], names=[item['URL']]) hosts.add([new], force=True, allow_address_duplication=True) hosts.write() time.sleep(30)
def create(self, vals): # Inherit create_portal.plan create method for generating template # name from server name and plan name. # Give warning if template is already exist. saas_server_obj = self.env['saas_portal.server'] portal_db_obj = self.env['saas_portal.database'] config = self.env['ir.config_parameter'] saas_config = self.env['saas_portal.config.settings'].search( [], limit=1, order="id desc") alies_name = saas_config.base_saas_domain if alies_name == False: base_saas_rec = config.search( [('key', '=', 'saas_portal.base_saas_domain')], limit=1) alies_name = base_saas_rec.value server_id = vals.get('server_id' or False) server_rec = saas_server_obj.browse(server_id) server_name = server_rec.name default_plan_name = vals.get('db_name') new_server_name = self.concate_string(server_name, alies_name) new_plan_name = self.concate_string(default_plan_name, alies_name) template_name = "template." + new_server_name + '.' + new_plan_name + \ '.' + alies_name exsiting_templates = portal_db_obj.search( [('name', '=', template_name), ('state', '=', 'template'), ('server_id', '=', server_id)], limit=1) if exsiting_templates: raise Warning( _('Template already exists. Please give Different ' 'Name of your Plan.')) else: # Host entry is done for the ip address and database name hosts = Hosts(path='/etc/hosts') new_entry = HostsEntry(entry_type='ipv4', address='127.0.0.1', names=[template_name]) hosts.add([new_entry]) hosts.write() portal_db_rec = portal_db_obj.create({ 'name': template_name, 'server_id': server_id }) vals.update({ 'template_id': portal_db_rec.id, }) return super(mint_plan_enhancement, self).create(vals)
def configure_environment(): # Descarga la private key de S3 if 'AWS_ACCESS_KEY_ID' in os.environ: s3 = boto3.client('s3') s3.download_file(STP_BUCKET_S3, STP_PRIVATE_KEY, STP_PRIVATE_LOCATION) # Edita archivo hosts si es necesario if os.environ['EDIT_HOSTS'] == 'true': host_ip = os.environ['HOST_IP'] host_ad = os.environ['HOST_AD'] hosts = Hosts() new_entry = HostsEntry(entry_type='ipv4', address=host_ip, names=[host_ad]) hosts.add([new_entry]) hosts.write()
def update_host(): nodes_address = [] for entry in hosts.entries: if entry.names is not None: for name in entry.names: if name.startswith('node'): nodes_address.append(entry.address) break for addr in nodes_address: hosts.remove_all_matching(address=addr) for name, ip in fog_map.items(): name = name.decode() name = name.strip('/').replace('/', '.') ip = ip.decode() new_entry = HostsEntry(entry_type='ipv4', address=ip, names=[name]) hosts.add([new_entry]) hosts.write()
def add_host( airflow_options: AirflowOptions, entry_type: str = "ipv4", address: Optional[str] = None, force: bool = False, ): if address is None: address = get_minikube_ip() my_hosts = Hosts() my_hosts.add( [ HostsEntry(entry_type, address=address, names=[airflow_options.domain_name]) ], force=force, ) my_hosts.write()
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()
def block(): # Remove previous blocks to prevent duplicates progress.set( "Processing hosts file" ) if sys.platform.startswith("win"): path = "C:\Windows\System32\drivers\etc\hosts" else: path = "/etc/hosts" hosts = Hosts(path) hosts.remove_all_matching(address="0.0.0.1") hosts.write() # Add domains to hosts file with IP 0.0.0.1 # 8 domains in a row (hosts file limitation) # https://superuser.com/questions/932112/is-there-a-maxium-number-of-hostname-aliases-per-line-in-a-windows-hosts-file for i in range(0, len(data), 8): new_entry = HostsEntry(entry_type='ipv4', address='0.0.0.1', names=data[i:(i+8)]) hosts.add([new_entry], False, True) progress.set( str( round(100*i/len(data),2)) + "%" ) hosts.write() progress.set( "100 %" ) status.set("DONE (You can close the program. Restart your browser.)")