当前位置: 首页>>代码示例>>Python>>正文


Python netaddr.IPAddress方法代码示例

本文整理汇总了Python中netaddr.IPAddress方法的典型用法代码示例。如果您正苦于以下问题:Python netaddr.IPAddress方法的具体用法?Python netaddr.IPAddress怎么用?Python netaddr.IPAddress使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在netaddr的用法示例。


在下文中一共展示了netaddr.IPAddress方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ip_address_from_address

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def ip_address_from_address(address):
    try:
        ip_address = netaddr.IPAddress(address)
    except ValueError as e:
        # address contains a CIDR prefix, netmask, or hostmask.
        e.message = ('invalid IP address: %(address)s (detected CIDR, netmask,'
                     ' hostmask, or subnet)') % {'address': address}
        raise
    except netaddr.AddrFormatError as e:
        # address is not an IP address represented in an accepted string
        # format.
        e.message = ("invalid IP address: '%(address)s' (failed to detect a"
                     " valid IP address)") % {'address': address}
        raise

    if ip_address.version == 4:
        return ip_address
    else:
        raise NotSupported(
            ('invalid IP address: %(address)s (Internet Protocol version'
             ' %(version)s is not supported)') % {
                'address': address,
                'version': ip_address.version}) 
开发者ID:dsp-jetpack,项目名称:JetPack,代码行数:25,代码来源:discover_nodes.py

示例2: setIps

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def setIps(vm, node):
        """
        Set the IPs of the VM from the info obtained from vSphere
        """
        public_ips = []
        private_ips = []

        if node.guest:
            for nic in node.guest.net:
                if nic.ipAddress:
                    ip = nic.ipAddress
                    is_private = any([IPAddress(ip) in IPNetwork(mask) for mask in Config.PRIVATE_NET_MASKS])
                    if is_private:
                        private_ips.append(ip)
                    else:
                        public_ips.append(ip)

        vm.setIps(public_ips, private_ips) 
开发者ID:grycap,项目名称:im,代码行数:20,代码来源:vSphere.py

示例3: setIPsFromTemplate

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def setIPsFromTemplate(vm, template):
        """
        Set the IPs of the VM from the info obtained in the ONE template object

        Arguments:
           - vm(:py:class:`IM.VirtualMachine`): VM information.
           - template(:py:class:`TEMPLATE`): ONE Template information.
        """
        system = vm.info.systems[0]
        for nic in template.NIC:
            i = 0
            while system.getValue("net_interface." + str(i) + ".connection"):
                net_name = system.getValue("net_interface." + str(i) + ".connection")
                net = vm.info.get_network_by_id(net_name)
                provider_id = net.getValue("provider_id")
                if provider_id == nic.NETWORK:
                    ip = str(nic.IP)
                    if IPAddress(ip).version == 6:
                        system.setValue("net_interface." + str(i) + ".ipv6", ip)
                    else:
                        system.setValue("net_interface." + str(i) + ".ip", ip)
                    break
                i += 1 
开发者ID:grycap,项目名称:im,代码行数:25,代码来源:OpenNebula.py

示例4: get_ipv6_addr_by_EUI64

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def get_ipv6_addr_by_EUI64(cidr, mac):
    """Generate a IPv6 addr by EUI-64 with CIDR and MAC

    :param str cidr: a IPv6 CIDR
    :param str mac: a MAC address
    :return: an IPv6 Address
    :rtype: netaddr.IPAddress
    """
    # Check if the prefix is IPv4 address
    is_ipv4 = netaddr.valid_ipv4(cidr)
    if is_ipv4:
        msg = "Unable to generate IP address by EUI64 for IPv4 prefix"
        raise TypeError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(cidr)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise TypeError('Bad prefix or mac format for generating IPv6 '
                        'address by EUI-64: %(prefix)s, %(mac)s:'
                        % {'prefix': cidr, 'mac': mac})
    except TypeError:
        raise TypeError('Bad prefix type for generate IPv6 address by '
                        'EUI-64: %s' % cidr) 
开发者ID:openstack,项目名称:tempest-lib,代码行数:26,代码来源:data_utils.py

示例5: _range_from_indicator

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def _range_from_indicator(self, indicator):
        if '-' in indicator:
            start, end = map(
                lambda x: int(netaddr.IPAddress(x)),
                indicator.split('-', 1)
            )
        elif '/' in indicator:
            ipnet = netaddr.IPNetwork(indicator)
            start = int(ipnet.ip)
            end = start+ipnet.size-1
        else:
            start = int(netaddr.IPAddress(indicator))
            end = start

        if (not (start >= 0 and start <= 0xFFFFFFFF)) or \
           (not (end >= 0 and end <= 0xFFFFFFFF)):
            LOG.error('%s - {%s} invalid IPv4 indicator',
                      self.name, indicator)
            return None, None

        return start, end 
开发者ID:PaloAltoNetworks,项目名称:minemeld-core,代码行数:23,代码来源:ipop.py

示例6: _process_item

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def _process_item(self, row):
        ipairs = super(EmergingThreatsIP, self)._process_item(row)

        result = []

        for i, v in ipairs:
            try:
                parsed_ip = netaddr.IPAddress(i)
            except:
                LOG.error('%s - invalid IP %s, ignored', self.name, i)
                continue

            if parsed_ip.version == 4:
                v['type'] = 'IPv4'
            elif parsed_ip.version == 6:
                v['type'] = 'IPv6'
            else:
                LOG.error('%s - unknown IP version %s, ignored', self.name, i)
                continue

            result.append([i, v])

        return result 
开发者ID:PaloAltoNetworks,项目名称:minemeld-core,代码行数:25,代码来源:proofpoint.py

示例7: assign_static_ip

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def assign_static_ip(self):
        """
        Set the static IP for the PF devices for mlx5_core driver
        """
        # This function assigns static IP for the PF devices
        pf_devices = self.get_pf_ids()
        if (not self.start_addr_PF) or (not self.net_mask):
            raise exceptions.TestSetupFail(
                "No IP / netmask found, please populate starting IP address for PF devices in configuration file")
        ip_addr = netaddr.IPAddress(self.start_addr_PF)
        for PF in pf_devices:
            ifname = utils_misc.get_interface_from_pci_id(PF)
            ip_assign = "ifconfig %s %s netmask %s up" % (
                ifname, ip_addr, self.net_mask)
            logging.info("assign IP to PF device %s : %s", PF,
                         ip_assign)
            cmd = process.system(ip_assign, shell=True, ignore_status=True)
            if cmd:
                raise exceptions.TestSetupFail("Failed to assign IP : %s"
                                               % cmd)
            ip_addr += 1
        return True 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:24,代码来源:test_setup.py

示例8: canonicalize

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def canonicalize(self, ip_str):
        """
        Parse an IP string for listen to IPAddress content.
        """
        try:
            if ':' in ip_str:
                self.version = 'ipv6'
                if '%' in ip_str:
                    ip_str, scope = ip_str.split('%')
                    self.scope = int(scope)
                self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr)
            else:
                self.version = 'ipv4'
                self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr)
        except socket.error as detail:
            if 'illegal IP address' in str(detail):
                self.addr = ip_str
                self.version = 'hostname' 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:22,代码来源:utils_net.py

示例9: is_ipv4

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def is_ipv4(instance):
    if not isinstance(instance, compat.str_types):
        return True

    try:
        address = netaddr.IPAddress(instance, version=4)
        # netaddr happly accepts, and expands "127.0" into "127.0.0.0"
        if str(address) != instance:
            return False
    except Exception:
        return False

    if instance == '0.0.0.0':  # RFC5735
        return False

    return True 
开发者ID:openstack,项目名称:designate,代码行数:18,代码来源:format.py

示例10: check_ip_in_policy

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def check_ip_in_policy(client_ip, policy):
    """
    This checks, if the given client IP is contained in a list like

       ["10.0.0.2", "192.168.2.1/24", "!192.168.2.12", "-172.16.200.1"]

    :param client_ip: The IP address in question
    :param policy: A string of single IP addresses, negated IP address and subnets.
    :return: tuple of (found, excluded)
    """
    client_found = False
    client_excluded = False
    # Remove empty strings from the list
    policy = list(filter(None, policy))
    for ipdef in policy:
        if ipdef[0] in ['-', '!']:
            # exclude the client?
            if IPAddress(client_ip) in IPNetwork(ipdef[1:]):
                log.debug(u"the client {0!s} is excluded by {1!s}".format(client_ip, ipdef))
                client_excluded = True
        elif IPAddress(client_ip) in IPNetwork(ipdef):
            client_found = True
    return client_found, client_excluded 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:25,代码来源:__init__.py

示例11: get_hostname

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def get_hostname(ip):
    """
    Return a hostname for a given IP address
    :param ip: IP address
    :type ip: IPAddress
    :return: hostname
    """
    machines = get_machines(ip=ip)
    if len(machines) > 1:
        raise Exception("Can not get unique ID for IP=%r. "
                        "More than one machine found." % ip)
    if len(machines) == 1:
        # There is only one machine in the list and we get its ID
        hostname = machines[0].hostname
        # return the first hostname
        if type(hostname) == list:
            hostname = hostname[0]
    else:
        raise Exception("There is no machine with IP={0!r}".format(ip))
    return hostname 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:22,代码来源:machine.py

示例12: has_ip

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def has_ip(self, ip):
        """
        Checks if the machine has the given IP.
        A machine might have more than one IP Address. The ip is then
        provided as a list
        :param ip: The IP address to search for
        :type ip: Netaddr IPAddress
        :return: True or false
        """
        # convert to IPAddress
        if isinstance(ip, string_types):
            ip = netaddr.IPAddress(ip)

        if type(self.ip) == list:
            return ip in self.ip
        elif type(self.ip) == netaddr.IPAddress:
            return ip == self.ip 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:19,代码来源:base.py

示例13: get_dict

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def get_dict(self):
        """
        Convert the object attributes to a dict
        :return: dict of attributes
        """
        ip = self.ip
        if type(self.ip) == list:
            ip = ["{0!s}".format(i) for i in ip]
        elif type(self.ip) == netaddr.IPAddress:
            ip = "{0!s}".format(ip)

        d = {"hostname": self.hostname,
             "ip": ip,
             "resolver_name": self.resolver_name,
             "id": self.id}
        return d 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:18,代码来源:base.py

示例14: process_ip

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def process_ip(self, ip_str, force_scope=True):

        created, ip = self.IPAddress.find_or_create(
            only_tool=True,
            ip_address=ip_str,
            in_scope=self.in_scope,
            passive_scope=self.passive_scope,
        )
        if not created:
            if ip.in_scope != self.in_scope or ip.passive_scope != self.passive_scope:
                display(
                    "IP %s already exists with different scoping. Updating to Active Scope: %s Passive Scope: %s"
                    % (ip_str, self.in_scope, self.passive_scope)
                )

                ip.in_scope = self.in_scope
                ip.passive_scope = self.passive_scope
                ip.update()
        return ip 
开发者ID:depthsecurity,项目名称:armory,代码行数:21,代码来源:Ingestor.py

示例15: descope_ip

# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPAddress [as 别名]
def descope_ip(self, ip):
        ip = self.IPAddress.all(ip_address=ip)
        if ip:
            for i in ip:
                display("Removing IP {} from scope".format(i.ip_address))
                i.in_scope = False
                i.passive_scope = False
                i.update()
                for d in i.domains:
                    in_scope_ips = [
                        ipa
                        for ipa in d.ip_addresses
                        if ipa.in_scope or ipa.passive_scope
                    ]
                    if not in_scope_ips:
                        display(
                            "Domain {} has no more scoped IPs. Removing from scope.".format(
                                d.domain
                            )
                        )
                        d.in_scope = False
                        d.passive_scope = False
            self.IPAddress.commit() 
开发者ID:depthsecurity,项目名称:armory,代码行数:25,代码来源:Ingestor.py


注:本文中的netaddr.IPAddress方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。