Ejemplo n.º 1
0
    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 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)
Ejemplo n.º 3
0
def test_get_entry_type():
    """
    Test that the correct entry type is returned for an ipv6 address
    """
    assert HostsEntry.get_entry_type('# This is a comment') == 'comment'
    assert HostsEntry.get_entry_type('\n') == 'blank'
    assert HostsEntry.get_entry_type('1.2.3.4 example.com example') == 'ipv4'
    assert HostsEntry.get_entry_type('2001:0db8:85a3:0042:1000:8a2e:0370:7334 example.com example') == 'ipv6'
    assert not HostsEntry.get_entry_type('example.com example 1.2.3.4')
Ejemplo n.º 4
0
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()
Ejemplo n.º 5
0
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
Ejemplo n.º 6
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 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
Ejemplo n.º 8
0
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")
Ejemplo n.º 9
0
    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.')
Ejemplo n.º 10
0
    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()
Ejemplo n.º 11
0
 def addEntry(self, name, destAddress):
     self.removeEntry(name)
     entry = HostsEntry(entry_type='ipv4',
                        address=destAddress,
                        names=[name])
     self.add([entry], True)
     return entry
Ejemplo n.º 12
0
 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()
Ejemplo n.º 13
0
    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()
Ejemplo n.º 14
0
 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()
Ejemplo n.º 15
0
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()
Ejemplo n.º 16
0
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()
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
 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()
Ejemplo n.º 19
0
 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()
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
def test_add_adblock_entry_without_force_multiple_names(tmpdir):
    """
    Test that addition of an adblock entry does not succeed if force is not set
    and there is a matching name
    """
    ipv4_line = '0.0.0.0 example2.com example3.com'
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write(ipv4_line)
    hosts_entries = Hosts(path=hosts_file.strpath)
    new_entry = HostsEntry.str_to_hostentry('0.0.0.0 example.com example3.com')
    hosts_entries.add(entries=[new_entry], force=False)
    assert hosts_entries.exists(names=['example2.com'])
Ejemplo n.º 22
0
def test_add_adblock_entry_with_force_single_name(tmpdir):
    """
    Test that an addition of an adblock entry replaces one with a matching name
    if force is True
    """
    ipv4_line = '0.0.0.0 example2.com example3.com'
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write(ipv4_line)
    hosts_entries = Hosts(path=hosts_file.strpath)
    new_entry = HostsEntry.str_to_hostentry('0.0.0.0 example.com example3.com')
    hosts_entries.add(entries=[new_entry], force=True)
    assert hosts_entries.exists(names=['example.com'])
Ejemplo n.º 23
0
 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])
Ejemplo n.º 24
0
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()
Ejemplo n.º 25
0
 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 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}")
Ejemplo n.º 27
0
 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)
Ejemplo n.º 28
0
def test_write_will_create_path_if_missing():
    """
    Test that the hosts file declared when constructing a Hosts instance will
    be created if it doesn't exist
    """
    now = datetime.datetime.now()
    timestamp = now.strftime('%Y%m%d%H%M%S')
    hosts_path = '/tmp/testwrite.{0}'.format(timestamp)
    hosts = Hosts(path=hosts_path)
    entry = HostsEntry.str_to_hostentry('1.2.3.4 example.com example.org')
    hosts.add(entries=[entry])
    hosts.write()
    hosts2 = Hosts(path=hosts_path)
    os.remove(hosts_path)
    assert hosts2.exists(address='1.2.3.4')
Ejemplo n.º 29
0
    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)
Ejemplo n.º 30
0
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()
Ejemplo n.º 31
0
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()
Ejemplo n.º 32
0
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()
Ejemplo n.º 33
0
def add(entry_line=None, hosts_path=None, force_add=False):
    """Add the specified entry

    :param entry_line: The entry to add
    :param hosts_path: The path of the hosts file
    :param force_add: Replace matching any matching entries with new entry
    :return: A dict containing the result and user message to output
    """
    hosts_entry = HostsEntry.str_to_hostentry(entry_line)
    if not hosts_entry:
        output_message({
            'result':
            'failed',
            'message':
            '"{0}": is not a valid entry.'.format(entry_line)
        })

    duplicate_entry = False
    entry_to_add = False

    hosts = Hosts(hosts_path)
    add_result = hosts.add(entries=[hosts_entry], force=force_add)
    if add_result.get('replaced_count'):
        hosts.write()
        return {
            'result': 'success',
            'message': 'Entry added. Matching entries replaced.'
        }
    if add_result.get('ipv4_count') or add_result.get('ipv6_count'):
        entry_to_add = True
    if add_result.get('duplicate_count'):
        duplicate_entry = True
    if entry_to_add and not duplicate_entry:
        hosts.write()
        return {'result': 'success', 'message': 'New entry added.'}
    if not force_add and duplicate_entry:
        return {
            'result':
            'failed',
            'message':
            'New entry matches one or more existing.'
            '\nUse -f to replace similar entries.'
        }
Ejemplo n.º 34
0
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()
Ejemplo n.º 35
0
def test_str_to_hostentry_ipv6():
    str_entry = HostsEntry.str_to_hostentry('2001:0db8:85a3:0042:1000:8a2e:0370:7334 example.com example')
    assert str_entry.entry_type == 'ipv6'
    assert str_entry.address == '2001:0db8:85a3:0042:1000:8a2e:0370:7334'
    assert str_entry.names == ['example.com', 'example']
Ejemplo n.º 36
0
def test_str_to_hostentry_ipv4():
    str_entry = HostsEntry.str_to_hostentry('10.10.10.10 example.com example.org example')
    assert str_entry.entry_type == 'ipv4'
    assert str_entry.address == '10.10.10.10'
    assert str_entry.names == ['example.com', 'example.org', 'example']
Ejemplo n.º 37
0
def test_str_to_hostentry_returns_fails_with_false():
    result = HostsEntry.str_to_hostentry('invalid example.com example')
    assert not result