def remove(address_to_remove=None, names_to_remove=None, remove_from_path=None): """Remove entries from a hosts file :param address_to_remove: An ipv4 or ipv6 address to remove :param names_to_remove: A list of names to remove :param remove_from_path: The path of the hosts file to remove entries from :return: A dict containing the result and user message to output """ hosts = Hosts(path=remove_from_path) if address_to_remove or names_to_remove: num_before = hosts.count() hosts.remove_all_matching(address=address_to_remove, name=names_to_remove) hosts.write() difference = num_before - hosts.count() if difference: if difference > 1: str_entry = 'entries' else: str_entry = 'entry' return { 'result': 'success', 'message': 'Removed {0} {1}'.format(difference, str_entry) } else: return {'result': 'failed', 'message': 'No matching entries found'}
def main(): hostentries = [] if os.environ['USER'] == "root": user = os.environ['SUDO_USER'] else: user = os.environ['USER'] with open("/Users/{}/.vagrant.d/data/machine-index/index".format(user), "r") as rawindex: currentvagrants = json.load(rawindex) for machine in currentvagrants['machines']: currentvagrants['machines'][machine]['machineprovider'] = currentvagrants['machines'][machine]['extra_data']['box']['provider'] with open("{local_data_path}/machines/{name}/{machineprovider}/vm".format(**currentvagrants['machines'][machine]), "r") as vmraw: vmdetails = yaml.load(vmraw) name = currentvagrants['machines'][machine]['name'] hostentries.append(HostsEntry(entry_type="ipv4", address=vmdetails['host'], names=["{}.vagrant.skytap.com".format(name), name, "vagrant"])) print("Updating host entry: {} with address: {}".format(name, vmdetails['host'])) hosts = Hosts("/private/etc/hosts") hosts.remove_all_matching(name="vagrant") hosts.add(hostentries) hosts.write()
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 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 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 test_remove_existing_ipv4_address_using_hostsentry(tmpdir): """ Test removal of an existing ip4 address """ ipv4_line = '1.2.3.4 example.com example' hosts_file = tmpdir.mkdir("etc").join("hosts") hosts_file.write(ipv4_line) hosts_entries = Hosts(path=hosts_file.strpath) assert hosts_entries.exists(address='1.2.3.4') assert hosts_entries.exists(names=['example.com']) hosts_entries.remove_all_matching(address='1.2.3.4', name='example.com') assert not hosts_entries.exists(address='1.2.3.4') assert not hosts_entries.exists(names=['example.com'])
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)
class HostsFileManager: def __init__(self): self.my_hosts = Hosts() 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 remove_entry(self, ip, name): name = name + ".dev" self.my_hosts.remove_all_matching(address=ip) self.my_hosts.remove_all_matching(name=name) self.my_hosts.write()
def write_file_entry(self, current_config=None, previous_config=None): f = Hosts(self.hosts_file) def _fmt(**kwargs): return self.pattern.format(**kwargs) 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]) for cfg in current_config, previous_config: if cfg is None: continue for _, addr in cfg.get('networks', {}).items(): if addr: logger.debug("Removing entries matching address: %s", addr) f.remove_all_matching(address=addr) for network, _ in cfg.get('networks', {}).items(): name = _fmt(name=cfg['name'], hostname=cfg['hostname'], network=network) logger.debug("Removing entries matching name: %s", name) f.remove_all_matching(name=name) if current_config: f.add(list(_gen_entries())) f.write()
def stopProject(name): if os.path.isdir("./" + name) == False: print( "Project does not exist, please choose another name or create it with command: python {} create {}" .format(sys.argv[0], name)) exit(0) settingsFile = "./" + name + "/settings" settings = importlib.import_module(".settings", package=name) dockerdbargs = ["docker", "stop", name + "-db"] dockerwpargs = ["docker", "stop", name + "-wp"] print("Stoping WP\n" + ' '.join(dockerwpargs)) os.system(' '.join(dockerwpargs)) print("Stoping DB\n" + ' '.join(dockerdbargs)) os.system(' '.join(dockerdbargs)) print("Restore rights") osargs = [ "sudo", "chown", "-R", "docker:docker", os.getcwd() + "/" + name + "/html/wp-content" ] os.system(' '.join(osargs)) osargs = [ "sudo", "chmod", "-R", "755", os.getcwd() + "/" + name + "/html/wp-content" ] os.system(' '.join(osargs)) print("Clear host") osargs = ["sudo", "chmod", "666", "/etc/hosts"] os.system(' '.join(osargs)) my_hosts = Hosts() my_hosts.remove_all_matching(name=settings.siteurl) my_hosts.write() osargs = ["sudo", "chmod", "644", "/etc/hosts"] os.system(' '.join(osargs))
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.)")
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
class HostsHandler(): ''' handle the Hosts object and the individual HostEntry objects ''' block_start = '### dnsmasq updater start ###' def __init__(self, file_handler, **kwargs): self.params = SimpleNamespace(**kwargs) self.logger = get_logger(self.__class__.__name__, self.params.log_level) self.file_handler = file_handler self.temp_file = file_handler.temp_file self.delayed_write = ResettableTimer(self.params.local_write_delay, self.write_hosts) self.get_remote_hosts() 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 parse_hostnames(self, hostnames): ''' return dictionary items containing IPs and a list of hostnames dict_items([ ('<IP_1>', ['<hostname1>', '<hostname2>', etc..]), ('<IP_2>', ['<hostname3>', '<hostname4>', etc..]), etc..]) ''' hostname_dict = defaultdict(set) for hostname in hostnames: host_ip = self.params.ip if ':' in hostname: hostname, host_ip = hostname.split(':', 1) try: hostname = hostname[0:hostname.index('.' + self.params.domain)] except ValueError: pass if not self.hosts.exists(names=[hostname]): hostname_dict[host_ip].update( [hostname, hostname + '.' + self.params.domain]) return dict([key, sorted(value)] for key, value in hostname_dict.items()) 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 del_hosts(self, hostnames): ''' delete hostnames, optionally write out ''' self.logger.debug('Deleting hostnames: %s', hostnames) for hostname in hostnames: try: hostname = hostname[0:hostname.index(':')] except ValueError: pass self.hosts.remove_all_matching(name=hostname) self.queue_write() def queue_write(self): ''' delayed writing of the local and remote hosts files the delay allows for any additional changes in the immediate future, such as expected when a container is restarting, for example. ''' self.delayed_write.reset() def write_hosts(self): ''' write local hosts file, put it on the remote device ''' if self.params.log_level == logging.DEBUG: self.logger.debug('Writing local hosts temp file: %s', self.temp_file.name) for entry in self.hosts.entries: print(' ', entry) self.hosts.write(path=self.temp_file.name) self.temp_file.seek(0) self.file_handler.queue_put()
if ip <> "Unknown": ip = IPAddress(ip) if ip <> "Unknown" and name <> None: name = name.replace(" ", "") list[ip] = name sorted(list) for entry in list.items(): ip = str(entry[0]) name = entry[1] new_entry = HostsEntry(entry_type='ipv4', address=ip, names=[name]) if hosts.exists(ip): hosts.remove_all_matching(ip) hosts.add([new_entry]) if args.verbose: print entry[0], '\t', entry[1] if args.verbose: if args.nohosts: print "--nohosts specified, not attempting to write to hosts file" if not args.nohosts: try: hosts.write() except: print "You need root permissions to write to /etc/hosts - skipping!" sys.exit(1)
etchostname = addressList[macaddress] print( f"Device at {ipaddress} ({macaddress}) is in our list as {etchostname}" ) else: print( f"Device at {ipaddress} ({macaddress}) is NOT in our list." ) break # if neither the hostname or ip address exist in hosts file if not hosts.exists(ipaddress, etchostname): print( f"Adding hostname: {etchostname} with {ipaddress} to hosts file." ) hosts.remove_all_matching(name=etchostname) new_entry = HostsEntry(entry_type='ipv4', address=ipaddress, names=[etchostname]) hosts.add([new_entry]) # if the hostname exists but ip address in hosts file differs from nmap scan for entry in hosts.entries: if entry.entry_type in ['ipv4', 'ipv6']: if entry.names[0] == etchostname: if entry.address != ipaddress: print( f"Updating hostname {etchostname} with {ipaddress}." ) hosts.remove_all_matching(name=etchostname) new_entry = HostsEntry(entry_type='ipv4',
class Watcher(object): #pylint: disable=too-many-instance-attributes '''Watch kubernetes api for service objects :param env: dict of environment variables (eg: os.environ) :param config: kubernetes.client.Configuration ''' def __init__(self, env=None, config=None): if env is None: env = {} if config is None: config = client.Configuration() LOGGER.info('Starting') lock_file_path = env.get('LOCK_FILE', '/var/lock/mirror-hostess') self.hosts_file_path = env.get('HOSTS_FILE', '/etc/hosts') self.hosts_file_backup_path = env.get('HOSTS_FILE_BACKUP', '/etc/hosts.backup') self.service_name = env.get('SERVICE_NAME', 'mirror-registry') self.service_namespace = env.get('SERVICE_NAMESPACE', 'default') self.shadow_fqdn = env.get('SHADOW_FQDN', 'mirror-registry.example.com') self.hostfile = Hosts(self.hosts_file_path) self.lock = filelock.FileLock(lock_file_path) api_client = client.ApiClient(config=config) self.v1_api = client.CoreV1Api(api_client=api_client) self.hostmap = {} self.watch = watch.Watch() def _cleanup(self, signum, frame): #pragma: no cover #pylint: disable=unused-argument ''' cleanup system on interrupt ''' LOGGER.info('Caught interrupt, cleaning up and exiting') self.watch.stop() self.remove_all_hosts() raise RuntimeError("Exiting") def remove_host(self, fqdn): ''' remove a host by fqdn ''' with self.lock.acquire(timeout=5): self.hostfile = Hosts(self.hosts_file_path) LOGGER.info("Removing entry for %s", fqdn) self.hostfile.remove_all_matching(name=fqdn) del self.hostmap[fqdn] self._write_hosts_file() 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 remove_all_hosts(self): ''' remove all previously added hosts ''' for fqdn in list(self.hostmap): self.remove_host(fqdn=fqdn) def _write_hosts_file(self): ''' write hosts file to disk ''' with self.lock.acquire(timeout=5): self.hostfile.write() def backup_etc_hosts(self): ''' simple file copy if destination does not already exist ''' LOGGER.debug("Hosts file at %s, backup to %s", self.hosts_file_path, self.hosts_file_backup_path) if os.path.exists(self.hosts_file_backup_path): LOGGER.warning("Backup hosts file already exists at %s", self.hosts_file_backup_path) try: shutil.copyfile(self.hosts_file_path, self.hosts_file_backup_path) except IOError as err: LOGGER.critical( "Unable to backup the hosts file to %s. [%s] Exiting for safety", self.hosts_file_backup_path, err) raise RuntimeError("Exiting") def execute(self): #pragma: no cover ''' main method ''' self.backup_etc_hosts() signal.signal(signal.SIGINT, self._cleanup) signal.signal(signal.SIGTERM, self._cleanup) self.watch_api() def watch_api(self): #pragma: no cover ''' watch service api endpoint, handle events ''' try: for event in self.watch.stream(self.v1_api.list_namespaced_service, namespace=self.service_namespace): self.handle_service_event(event) except ApiException as e: LOGGER.exception("Error watching custom object events", exc_info=True) def handle_service_event(self, event): ''' if expected service, add/remove host ''' service = event['object'] if (service.metadata.name == self.service_name and service.metadata.namespace == self.service_namespace): if event['type'] == 'ADDED' or event['type'] == 'MODIFIED': self.add_host(fqdn=self.shadow_fqdn, ip_addr=service.spec.cluster_ip) elif event['type'] == 'DELETED': self.remove_host(fqdn=self.shadow_fqdn) else: LOGGER.warning("Unexpected event type %s", event['type']) else: LOGGER.debug("Ignoring event for %s in %s", service.metadata.name, service.metadata.namespace)
class MulticastAnnouncerListener: def __init__(self, **kwargs): self.MCAST_GROUP = '224.1.1.1' self.MCAST_PORT = 4180 self.IS_ALL_GROUPS = True self.blacklisted_interfaces = ['lo', 'lo0'] self.blacklisted_ips = [] self.localSubnets = [] self.ips = {} self.logfile = kwargs['l'] self.hostsfile = kwargs['o'] self.input_hostsfile = kwargs['i'] self.seperator = kwargs['s'] self.verbose = kwargs['v'] self.name = kwargs['nickname'] self.blacklist = str(kwargs['bl']).split(",") self.blacklisted_subnets = [] self.log = logging.getLogger(__name__) syslog = logging.StreamHandler() formatter = logging.Formatter("%(message)s") syslog.setFormatter(formatter) self.log.setLevel(logging.DEBUG) self.log.addHandler(syslog) self.log = logging.LoggerAdapter(self.log, {'app_name': 'muCast'}) if self.input_hostsfile and not self.hostsfile: self.log.error( '[ERROR] You can only import a hosts file if you are also writing a hosts file via -o' ) os._exit(1) if self.hostsfile: self.hosts = Hosts(path=self.hostsfile) else: self.hosts = False if os.path.exists(self.input_hostsfile) and os.path.isfile( self.input_hostsfile) and self.input_hostsfile: imported = self.hosts.import_file(self.input_hostsfile) self.log.debug('[ OK ] Imported hosts file: {}'.format( self.input_hostsfile)) elif self.input_hostsfile: self.log.error( '[ERROR] The hosts file to import {} does not exist or no permission has been given to read it' .format(self.input_hostsfile)) os._exit(1) if not self.logfile: self.log.debug("[ OK ] Writing to stdout") else: self.log.debug('[ OK ] Writing to logfile: {}'.format( self.logfile)) sys.stdout.flush() sys.stderr.flush() self.blacklistedSubnets() localSubnets = threading.Thread(target=self.getLocalSubnets, args=()).start() receive = threading.Thread(target=self.receive, args=()).start() def getLocalSubnets(self): while True: blacklisted_ips = [] localSubnets = [] for inter in netifaces.interfaces(): if inter not in self.blacklisted_interfaces: interface = netifaces.ifaddresses(inter) for address in interface: blacklisted_ips.append(interface[address][0]['addr']) try: bits = None ip_addr = None if 'netmask' in interface[address][0].keys(): netmask = interface[address][0]['netmask'] bits = IPAddress(netmask).netmask_bits() if 'addr' in interface[address][0].keys(): ip_addr = interface[address][0]['addr'] cidr = "{}/{}".format(ip_addr, bits) localSubnets.append( ipaddress.ip_network(cidr, False)) except Exception as e: #if self.verbose: self.log.error("[LISTENER - getLocalSubnets() - (Try/Catch statement)]: {}".format(e)) pass self.blacklisted_ips = blacklisted_ips self.localSubnets = localSubnets time.sleep(1) def blacklistedSubnets(self): for subnet in self.blacklist: try: self.blacklisted_subnets.append(IPNetwork(str(subnet))) except: pass def receive(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.IS_ALL_GROUPS: sock.bind(('', self.MCAST_PORT)) else: socket.bind((self.MCAST_GROUP, self.MCAST_PORT)) mreq = struct.pack("4sl", socket.inet_aton(self.MCAST_GROUP), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) while True: recv = sock.recv(10240).decode("utf-8") self.parseResponse(recv) def parseResponse(self, recv): try: nickname = recv.split(":")[0] address = ipaddress.ip_address(recv.split(":")[1]) packet_id = recv.split(":")[2] timestamp = recv.split(":")[3] if self.verbose: self.log.debug( "[VERBOSE] Packet {} from {} with content {} received at {} ({} difference in ms)" .format(packet_id, nickname, address, timestamp, ((time.time() - float(timestamp)) / 1000))) for subnet in self.localSubnets: subnet = IPNetwork(str(subnet)) ip = IPAddress(str(address)) is_blacklisted = False for b_subnet in self.blacklisted_subnets: if ip in b_subnet: is_blacklisted = True if ip in subnet and nickname != self.name and not is_blacklisted: self.ips[nickname] = address if self.logfile: self.writeLogFile() if self.hosts: self.writeHostsFile(recv) self.log.info( codecs.decode(("{}{}{}".format(address, self.seperator, nickname)), 'unicode_escape')) except Exception as e: if self.verbose and "does not appear to be an IPv4 or IPv6 address" not in str( e): self.log.error("[LISTENER - parseResponse()]: {}".format(e)) else: pass def writeLogFile(self): with open(self.logfile, 'w') as file: file_content = "" for nickname in self.ips: ip = self.ips[nickname] file_content += "{}{}{}\n".format(ip, self.seperator, nickname) file.write(codecs.decode(file_content, 'unicode_escape')) file.close() 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
from python_hosts import Hosts, HostsEntry import requests hosts = Hosts(path='C:\Windows\System32\drivers\etc\hosts') r = requests.get('http://dev.nsyncdata.net:9000/hosts') r = r.json() #print (r['Add'][0]['Address']) for item in r['Remove']: print(item['URL']) hosts.remove_all_matching(name=item['URL']) for item in r['Add']: print(item['URL']) new = HostsEntry(entry_type='ipv4', address=item['Address'], names=[item['URL']]) hosts.add([new], force=True, allow_address_duplication=True) hosts.write() print(hosts)
def delete_host(): """ Delete hosts entry for the server IP """ hosts = Hosts() hosts.remove_all_matching(GCEMetadata.IP) hosts.write()
from python_hosts import Hosts, HostsEntry import subprocess my_hosts = Hosts(path="C:\\Windows\\System32\\drivers\\etc\\hosts") print(" PointBlank Server UDP3 By MoMzGames ") print(" RESTORE SERVER ") print(" by un4ckn0wl3z ") print("======================================") my_hosts.remove_all_matching(address='45.76.187.53') my_hosts.write() result = subprocess.Popen("w32tm /resync", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = result.communicate() print(output) result = subprocess.Popen("ipconfig /flushdns ", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = result.communicate() print(output)
while True: for container in CLIENT.containers.list(): networks = container.attrs['NetworkSettings']['Networks'] conf = container.attrs['Config'] if not (conf['Hostname'] and conf['Domainname']): continue hostname = '{}.{}'.format(conf['Hostname'], conf['Domainname']) for nw_name in networks: network = networks[nw_name] ip = network['IPAddress'] if DNS_FILTER_CONTAINS in hostname: if container.status == 'running': if hostname not in ENTRIES: ENTRIES[hostname] = HostsEntry( entry_type='ipv4', address=ip, names=[hostname]) logger.info('add %s to HOSTS', hostname) HOSTS.add([ENTRIES[hostname]]) else: if hostname in ENTRIES: del ENTRIES[hostname] HOSTS.remove_all_matching(name=hostname) logger.info('remove %s from HOSTS', hostname) HOSTS.write() sleep(DNS_REFRESH_TIME_S)