當前位置: 首頁>>代碼示例>>Python>>正文


Python pyroute2.IPRoute方法代碼示例

本文整理匯總了Python中pyroute2.IPRoute方法的典型用法代碼示例。如果您正苦於以下問題:Python pyroute2.IPRoute方法的具體用法?Python pyroute2.IPRoute怎麽用?Python pyroute2.IPRoute使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pyroute2的用法示例。


在下文中一共展示了pyroute2.IPRoute方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def __init__(self, simulated_interfaces, table_name, log, log_id):
        self._simulated_interfaces = simulated_interfaces
        self._table_name = table_name
        if isinstance(table_name, int):
            self._table_nr = table_name
        else:
            self._table_nr = self.table_name_to_nr(table_name)
        self._log = log
        self._log_id = log_id
        self.debug("Create kernel using route table %s" % table_name)
        try:
            self.ipr = pyroute2.IPRoute()
            self.platform_supported = True
            self.debug("Kernel networking is supported on this platform")
        except OSError:
            self.ipr = None
            self.platform_supported = False
            self.warning("Kernel networking is not supported on this platform") 
開發者ID:brunorijsman,項目名稱:rift-python,代碼行數:20,代碼來源:kernel.py

示例2: __pyroute2_get_host_by_ip

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def __pyroute2_get_host_by_ip(ip):
    import pyroute2
    ipr = pyroute2.IPRoute()
    routes = ipr.get_routes(family=socket.AF_INET, dst=ip)
    ipr.close()
    for route in routes:
        for attr in route.get('attrs', []):
            if type(attr) is list:
                if attr[0] == 'RTA_PREFSRC':
                    return attr[1]
            else:
                if attr.cell[0] == 'RTA_PREFSRC':
                    return attr.get_value()
    logger.critical(
        '__pyroute2_get_host_by_ip() - No host found for IP {}!'.format(ip))
    return None 
開發者ID:masmu,項目名稱:pulseaudio-dlna,代碼行數:18,代碼來源:network.py

示例3: _interface_by_mac

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def _interface_by_mac(self, mac):
        try:
            with pyroute2.IPRoute() as ipr:
                idx = ipr.link_lookup(address=mac)[0]
                addr = ipr.get_links(idx)[0]
                for attr in addr['attrs']:
                    if attr[0] == 'IFLA_IFNAME':
                        return attr[1]
        except Exception as e:
            LOG.info('Unable to find interface with MAC: %s, rescanning '
                     'and returning 404. Reported error: %s', mac, str(e))

        # Poke the kernel to re-enumerate the PCI bus.
        # We have had cases where nova hot plugs the interface but
        # the kernel doesn't get the memo.
        filename = '/sys/bus/pci/rescan'
        flags = os.O_WRONLY
        if os.path.isfile(filename):
            with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
                rescan_file.write('1')
        raise exceptions.HTTPException(
            response=webob.Response(json=dict(
                details="No suitable network interface found"), status=404)) 
開發者ID:openstack,項目名稱:octavia,代碼行數:25,代碼來源:plug.py

示例4: get_interface_name

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def get_interface_name(ip_address, net_ns=None):
    """Gets the interface name from an IP address.

    :param ip_address: The IP address to lookup.
    :param net_ns: The network namespace to find the interface in.
    :returns: The interface name.
    :raises exceptions.InvalidIPAddress: Invalid IP address provided.
    :raises octavia.common.exceptions.NotFound: No interface was found.
    """
    # We need to normalize the address as IPv6 has multiple representations
    # fe80:0000:0000:0000:f816:3eff:fef2:2058 == fe80::f816:3eff:fef2:2058
    try:
        normalized_addr = ipaddress.ip_address(ip_address).compressed
    except ValueError:
        raise exceptions.InvalidIPAddress(ip_addr=ip_address)

    if net_ns:
        with pyroute2.NetNS(net_ns) as rtnl_api:
            interface = _find_interface(ip_address, rtnl_api, normalized_addr)
    else:
        with pyroute2.IPRoute() as rtnl_api:
            interface = _find_interface(ip_address, rtnl_api, normalized_addr)
    if interface is not None:
        return interface
    raise exceptions.NotFound(resource='IP address', id=ip_address) 
開發者ID:openstack,項目名稱:octavia,代碼行數:27,代碼來源:network_utils.py

示例5: condUnshareNet

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def condUnshareNet(unshare_net=True):
    if USE_NSPAWN and unshare_net:
        try:
            unshare(CLONE_NEWNET)
            # Set up loopback interface and add default route via loopback in the namespace.
            # Missing default route may confuse some software, see
            # https://github.com/rpm-software-management/mock/issues/113
            ipr = IPRoute()
            dev = ipr.link_lookup(ifname='lo')[0]

            ipr.link('set', index=dev, state='up')
            ipr.route("add", dst="default", gateway="127.0.0.1")
        except exception.UnshareFailed:
            # IPC and UTS ns are supported since the same kernel version. If this
            # fails, there had to be a warning already
            pass
        except Exception as e: # pylint: disable=broad-except
            getLog().warning("network namespace setup failed: %s", e) 
開發者ID:rpm-software-management,項目名稱:mock,代碼行數:20,代碼來源:util.py

示例6: __init__

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def __init__(self, reactor, protocol, name, addr, dev=b'/dev/net/tun', mtu=1400, mode=TUN):
        abstract.FileDescriptor.__init__(self, reactor)
        self.queue = deque()
        self.mtu = mtu
        self.name = name
        self.fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK)

        try:
            # We don't need packet info
            mode |= self.IFF_NO_PI
            fcntl.ioctl(self.fd, self.TUNSETIFF, struct.pack('16sH', bytes(name, 'ascii'), mode))
            with closing(IPRoute()) as ip:
                ifidx = ip.link_lookup(ifname=name)[0]
                _addr, _mask = addr.split('/')
                ip.link('set', index=ifidx, state='up', mtu=self.mtu)
                ip.addr('add', index=ifidx, address=_addr, prefixlen=int(_mask))
        except Exception:
            os.close(self.fd)
            raise

        # Connect protocol
        self.protocol = protocol
        self.protocol.makeConnection(self)
        self.connected = 1
        self.startReading() 
開發者ID:svpcom,項目名稱:wifibroadcast,代碼行數:27,代碼來源:tuntap.py

示例7: attach_interface_to_bridge

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def attach_interface_to_bridge(interface_index, bridge_name):
        from pyroute2 import IPRoute
        ip = IPRoute()

        logging.debug("Attaching interface ID = %d to bridge `%s`..." % (interface_index, bridge_name))
        bridge_index = ip.link_lookup(ifname=bridge_name)[0]

        ip.link(
            "set",
            index=interface_index,
            master=bridge_index,
            state="up"
        )

        logging.debug("Interface ID = %d attached to bridge %s." % (interface_index, bridge_name))

        ip.close() 
開發者ID:KatharaFramework,項目名稱:Kathara,代碼行數:19,代碼來源:Networking.py

示例8: remove_interface

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def remove_interface(interface_name):
        from pyroute2 import IPRoute
        ip = IPRoute()

        logging.debug("Searching for interface `%s`..." % interface_name)

        # Search the interface
        link_indexes = ip.link_lookup(ifname=interface_name)
        # If not present, raise an error
        if not link_indexes:
            logging.debug("Interface `%s` not found, exiting..." % interface_name)
            return

        link_index = link_indexes[0]
        logging.debug("Interface found with ID = %d" % link_index)

        logging.debug("Removing interface with ID = %d" % link_index)
        ip.link(
            "del",
            index=link_index
        )

        ip.close() 
開發者ID:KatharaFramework,項目名稱:Kathara,代碼行數:25,代碼來源:Networking.py

示例9: __init__

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def __init__(self,
                 interface="deckard",
                 ip4_range=IPv4Network('127.127.0.0/16'),
                 ip6_range=IPv6Network('fd00:dec::/32')):
        self.ip4_internal_range = ip4_range
        self.ip6_internal_range = ip6_range
        self.ip4_iterator = (host for host in ip4_range)
        self.ip6_iterator = (host for host in ip6_range)
        self.added_addresses = set()
        self.interface = interface

        self._ip = IPRoute()
        try:
            self._dev = self._setup_interface()
        except NetlinkError:
            raise RuntimeError(f"Couldn't set interface `{self.interface}` up.") 
開發者ID:CZ-NIC,項目名稱:deckard,代碼行數:18,代碼來源:networking.py

示例10: _set_vf_mac

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def _set_vf_mac(self, pf, vf_index, mac):
        LOG.debug("Setting VF MAC: pf = %s, vf_index = %s, mac = %s",
                  pf, vf_index, mac)

        ip = pyroute2.IPRoute()
        pf_index = ip.link_lookup(ifname=pf)[0]
        try:
            ip.link("set", index=pf_index, vf={"vf": vf_index, "mac": mac})
        except pyroute2.netlink.exceptions.NetlinkError:
            LOG.exception("Unable to set mac for VF %s on pf %s",
                          vf_index, pf)
            raise 
開發者ID:openstack,項目名稱:kuryr-kubernetes,代碼行數:14,代碼來源:sriov.py

示例11: _set_vf_vlan

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def _set_vf_vlan(self, pf, vf_index, vlan_id):
        LOG.debug("Setting VF VLAN: pf = %s, vf_index = %s, vlan_id = %s",
                  pf, vf_index, vlan_id)
        ip = pyroute2.IPRoute()
        pf_index = ip.link_lookup(ifname=pf)[0]
        try:
            ip.link("set", index=pf_index, vf={"vf": vf_index,
                                               "vlan": vlan_id})
        except pyroute2.netlink.exceptions.NetlinkError:
            LOG.exception("Unable to set vlan for VF %s on pf %s",
                          vf_index, pf)
            raise 
開發者ID:openstack,項目名稱:kuryr-kubernetes,代碼行數:14,代碼來源:sriov.py

示例12: _find_interface

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def _find_interface(ip_address, rtnl_api, normalized_addr):
    """Find the interface using a routing netlink API.

    :param ip_address: The IP address to search with.
    :param rtnl_api: A pyroute2 rtnl_api instance. (IPRoute, NetNS, etc.)
    :returns: The interface name if found, None if not found.
    :raises exceptions.InvalidIPAddress: Invalid IP address provided.
    """
    for addr in rtnl_api.get_addr(address=ip_address):
        # Save the interface index as IPv6 records don't list a textual
        # interface
        interface_idx = addr['index']
        # Search through the attributes of each address record
        for attr in addr['attrs']:
            # Look for the attribute name/value pair for the address
            if attr[0] == 'IFA_ADDRESS':
                # Compare the normalized address with the address we are
                # looking for.  Since we have matched the name above, attr[1]
                # is the address value
                if normalized_addr == ipaddress.ip_address(attr[1]).compressed:
                    # Lookup the matching interface name by getting the
                    # interface with the index we found in the above address
                    # search
                    lookup_int = rtnl_api.get_links(interface_idx)
                    # Search through the attributes of the matching interface
                    # record
                    for int_attr in lookup_int[0]['attrs']:
                        # Look for the attribute name/value pair that includes
                        # the interface name
                        if int_attr[0] == 'IFLA_IFNAME':
                            # Return the matching interface name that is in
                            # int_attr[1] for the matching interface attribute
                            # name
                            return int_attr[1]
    # We didn't find an interface with that IP address.
    return None 
開發者ID:openstack,項目名稱:octavia,代碼行數:38,代碼來源:network_utils.py

示例13: set_net

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def set_net(lease):
    ipr = IPRoute()
    try:
        index = ipr.link_lookup(ifname=lease.interface)[0]
    except IndexError as e:
        logger.error('Interface %s not found, can not set IP.',
                     lease.interface)
    try:
        ipr.addr('add', index, address=lease.address,
                 mask=int(lease.subnet_mask_cidr))
    except NetlinkError as e:
        if ipr.get_addr(index=index)[0].\
                get_attrs('IFA_ADDRESS')[0] == lease.address:
            logger.debug('Interface %s is already set to IP %s' %
                         (lease.interface, lease.address))
        else:
            logger.error(e)
    else:
        logger.debug('Interface %s set to IP %s' %
                     (lease.interface, lease.address))
    try:
        ipr.route('add', dst='0.0.0.0', gateway=lease.router, oif=index)
    except NetlinkError as e:
        if ipr.get_routes(table=254)[0].\
                get_attrs('RTA_GATEWAY')[0] == lease.router:
            logger.debug('Default gateway is already set to %s' %
                         (lease.router))
        else:
            logger.error(e)
    else:
        logger.debug('Default gateway set to %s', lease.router)
    ipr.close()
    set_dns(lease) 
開發者ID:juga0,項目名稱:dhcpcanon,代碼行數:35,代碼來源:netutils.py

示例14: set_dns_systemd_resolved

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def set_dns_systemd_resolved(lease):
    # NOTE: if systemd-resolved is not already running, we might not want to
    # run it in case there's specific system configuration for other resolvers
    ipr = IPRoute()
    index = ipr.link_lookup(ifname=lease.interface)[0]
    # Construct the argument to pass to DBUS.
    # the equivalent argument for:
    # busctl call org.freedesktop.resolve1 /org/freedesktop/resolve1 \
    # org.freedesktop.resolve1.Manager SetLinkDNS 'ia(iay)' 2 1 2 4 1 2 3 4
    # is SetLinkDNS(2, [(2, [8, 8, 8, 8])]_
    iay = [(2, [int(b) for b in ns.split('.')])
           for ns in lease.name_server.split()]
    #        if '.' in ns
    #        else (10, [ord(x) for x in
    #            socket.inet_pton(socket.AF_INET6, ns)])
    bus = SystemBus()
    resolved = bus.get_object('org.freedesktop.resolve1',
                              '/org/freedesktop/resolve1')
    manager = Interface(resolved,
                        dbus_interface='org.freedesktop.resolve1.Manager')
    try:
        manager.SetLinkDNS(index, iay)
        return True
    except DBusException as e:
        logger.error(e)
        return False 
開發者ID:juga0,項目名稱:dhcpcanon,代碼行數:28,代碼來源:netutils.py

示例15: setup_routes

# 需要導入模塊: import pyroute2 [as 別名]
# 或者: from pyroute2 import IPRoute [as 別名]
def setup_routes(self, gateway):
        ip = pyroute2.IPRoute()

        for route in set(self.routes):
            net = ipaddress.IPv4Network(unicode(route))
            dst = '%s/%d' % (net.network_address, net.prefixlen)
            ip.route("add", dst=dst, gateway=gateway)

        logging.info("Remote routing configured, VPN is up") 
開發者ID:abrasive,項目名稱:nxBender,代碼行數:11,代碼來源:nx.py


注:本文中的pyroute2.IPRoute方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。