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


Python IPRoute.get_links方法代码示例

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


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

示例1: test_close

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
    def test_close(self):
        ip = IPRoute()
        ip.get_links()
        ip.close()

        # Shouldn't be able to use the socket after closing
        with assert_raises(socket.error):
            ip.get_links()
开发者ID:svinota,项目名称:pyroute2,代码行数:10,代码来源:test_ipr.py

示例2: TrafficControl

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
class TrafficControl(object, metaclass=Singleton):
    def __init__(self):
        self.mIpr = IPRoute()
        self.mInterfaces = {}
        self.InterfaceDiscovery()
        self.markIdGenerator = 0;

    def InterfaceDiscovery(self):
        rawInts = self.mIpr.get_links()
        for interface in rawInts:
            ifname = interface.get_attr('IFLA_IFNAME')
            ifindex = interface['index']
            #print ifname, ifindex
            newInt = Interface(ifname, ifindex, self.mIpr)
            self.mInterfaces[ifname] = newInt

    def getInterface(self, name):
        return self.mInterfaces[name]

    def generateMark(self):
        self.markIdGenerator += 1
        return self.markIdGenerator

    def cleanIpTables(self):
        chainNames = ["PREROUTING", "INPUT", "FORWARD", "OUTPUT", "POSTROUTING"]
        for name in chainNames:
            chain = iptc.Chain(iptc.Table(iptc.Table.MANGLE), name)
            chain.flush()
开发者ID:wishful-project,项目名称:python-tc,代码行数:30,代码来源:TrafficControl.py

示例3: scan_netdevs

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
def scan_netdevs():
    scan = []
    ipr = IPRoute()

    try:
        for part in ipr.get_links():
            new_link = {}
            new_link["netlink_msg"] = part
            new_link["index"] = part["index"]
            new_link["name"] = part.get_attr("IFLA_IFNAME")
            #
            # FIXME:
            #
            # nlmsg.get_attr() returns None if there is no
            # such attribute in the NLA chain; if hwaddr is None,
            # normalize_hwaddr(hwaddr) will raise AttributeError(),
            # since None has no upper(). The issue is that the
            # AttributeError() will be a bit unrelated to the
            # root cause, and since that it will be confusing.
            #
            hwaddr = part.get_attr("IFLA_ADDRESS")
            new_link["hwaddr"] = normalize_hwaddr(hwaddr)
            scan.append(new_link)
    except:
        raise
    finally:
        ipr.close()
    return scan
开发者ID:aloughlam,项目名称:lnst,代码行数:30,代码来源:NetUtils.py

示例4: scan_netdevs

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
def scan_netdevs():
    scan = []
    ipr = IPRoute()

    try:
        for part in ipr.get_links():
            new_link = {}
            new_link["netlink_msg"] = part
            new_link["index"] = part["index"]
            new_link["name"] = part.get_attr("IFLA_IFNAME")

            hwaddr = part.get_attr("IFLA_ADDRESS")
            if hwaddr:
                new_link["hwaddr"] = normalize_hwaddr(hwaddr)
            else:
                new_link["hwaddr"] = None

            addrs = ipr.get_addr(index=new_link["index"])
            new_link["ip_addrs"] = addrs

            scan.append(new_link)
    except:
        raise
    finally:
        ipr.close()
    return scan
开发者ID:idosch,项目名称:lnst,代码行数:28,代码来源:NetUtils.py

示例5: test_iproute

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
 def test_iproute(self):
     ip = IPRoute()
     try:
         assert len(ip.get_links()) > 1
     except:
         raise
     finally:
         ip.close()
开发者ID:0xD3ADB33F,项目名称:pyroute2,代码行数:10,代码来源:test_eventlet.py

示例6: getInterfaceState

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
def getInterfaceState(ifname):
    try:
        ip = IPRoute()
        state = ip.get_links(ip.link_lookup(ifname=ifname))[0].get_attr('IFLA_OPERSTATE')
        ip.close()
    except Exception as e:
        raise Exception("getInterfaceState: Collecting interface status for %s failed: %s" % (ifname,str(e)))
    else:
        if state == "UP":
            return True
    return False
开发者ID:piconsole,项目名称:picon,代码行数:13,代码来源:utils.py

示例7: test_fileno

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
    def test_fileno(self):
        require_python(3)
        ip1 = IPRoute()
        ip2 = IPRoute(fileno=ip1.fileno())

        ip2.bind()
        try:
            ip1.bind()
        except OSError as e:
            if e.errno != 22:  # bind -> Invalid argument
                raise

        ip1.close()
        try:
            ip2.get_links()
        except OSError as e:
            if e.errno != 9:   # sendto -> Bad file descriptor
                raise

        try:
            ip2.close()
        except OSError as e:
            if e.errno != 9:   # close -> Bad file descriptor
                raise
开发者ID:svinota,项目名称:pyroute2,代码行数:26,代码来源:test_ipr.py

示例8: main

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
def main():
	parser = argparse.ArgumentParser(description='Collect node information for alfred.')
	parser.add_argument('--prefix', dest='prefix', default='', help='Add hostname prefix')
	parser.add_argument('--interface', dest='interface', default='bat0', help='Local mesh interface')
	args = parser.parse_args()

	ip = IPRoute()
	ifattrs = [(iface['index'], dict(iface['attrs'])) for iface in ip.get_links()]

	try:
		meshif = [(attrs[0], attrs[1]['IFLA_ADDRESS']) for attrs in ifattrs if attrs[1]['IFLA_IFNAME'] == args.interface][0]
	except IndexError:
		sys.exit('Mesh interface %s not found.' % args.interface)


	mesh_interfaces = {'wireless': [], 'tunnel': [], 'other': []}
	for index, attrs in ifattrs:
		linkinfo = dict(attrs['IFLA_LINKINFO']['attrs'])
		if not linkinfo.get('IFLA_INFO_SLAVE_KIND') == 'batadv':
			continue

		kind = linkinfo.get('IFLA_INFO_KIND')
		if kind == 'tun':
			mesh_interfaces['tunnel'].append(attrs['IFLA_ADDRESS'])
		elif kind == 'gretap':
			mesh_interfaces['other'].append(attrs['IFLA_ADDRESS'])
		elif kind == 'dummy':
			mesh_interfaces['tunnel'].append(attrs['IFLA_ADDRESS'])
		else:
			continue

	addresses = [dict(addr['attrs'])['IFA_ADDRESS'] for addr in ip.get_addr() if addr['index'] == meshif[0] and addr['family'] == 10]

	result = {
		'node_id': meshif[1].replace(':', ''),
		'network': {
			'mac': meshif[1],
			'addresses': addresses,
			'mesh': {
				'bat0': {
					'interfaces': mesh_interfaces
				}
			}
		},
		'hostname': '%s%s' % (args.prefix, gethostname()),
	}

	json.dump(result, sys.stdout, separators=(',', ':'))
开发者ID:eulenfunk,项目名称:ff-tools,代码行数:50,代码来源:nodeinfo.py

示例9: __init__

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
 def __init__(self):
     ip = IPRoute()
     pppLinksIds = ip.link_lookup(ifname=INTERFACE)
     if len(pppLinksIds) > 0:
         state = ip.get_links(pppLinksIds)[0].get_attr('IFLA_OPERSTATE')
         if state == 'UP':
             self.connect = True
             self.details = INTERFACE + " interface UP"
         else:
             self.connect = False
             self.details = INTERFACE + " exist but no UP"
         ip.close()
     else:
         self.connect = False
         self.details = INTERFACE + " interface no exist"
     super(StatusSchema, self).__init__()
开发者ID:RahimovIR,项目名称:pppoe_web,代码行数:18,代码来源:app.py

示例10: TestMisc

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
class TestMisc(object):

    def setup(self):
        self.ip = IPRoute()

    def teardown(self):
        self.ip.close()

    def test_get_policy_map(self):
        assert isinstance(self.ip.get_policy_map(), dict)

    def test_register_policy(self):
        self.ip.register_policy(100, nlmsg)
        self.ip.register_policy({101: nlmsg})
        self.ip.register_policy(102, nlmsg)

        assert self.ip.get_policy_map()[100] == nlmsg
        assert self.ip.get_policy_map(101)[101] == nlmsg
        assert self.ip.get_policy_map([102])[102] == nlmsg

        self.ip.unregister_policy(100)
        self.ip.unregister_policy([101])
        self.ip.unregister_policy({102: nlmsg})

        assert 100 not in self.ip.get_policy_map()
        assert 101 not in self.ip.get_policy_map()
        assert 102 not in self.ip.get_policy_map()

    def test_addrpool_expand(self):
        # see coverage
        for i in range(100):
            self.ip.get_addr()

    def test_nla_compare(self):
        lvalue = self.ip.get_links()
        rvalue = self.ip.get_links()
        assert lvalue is not rvalue
        if lvalue == rvalue:
            pass
        if lvalue != rvalue:
            pass
        assert lvalue != 42
开发者ID:svinota,项目名称:pyroute2,代码行数:44,代码来源:test_ipr.py

示例11: TestMisc

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
class TestMisc(object):

    def setup(self):
        self.ip = IPRoute()

    def teardown(self):
        self.ip.close()

    def test_addrpool_expand(self):
        # see coverage
        for i in range(100):
            self.ip.get_addr()

    def test_nla_compare(self):
        lvalue = self.ip.get_links()
        rvalue = self.ip.get_links()
        assert lvalue is not rvalue
        if lvalue == rvalue:
            pass
        if lvalue != rvalue:
            pass
        assert lvalue != 42
开发者ID:jazzmes,项目名称:pyroute2,代码行数:24,代码来源:test_ipr.py

示例12: network_module

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]

#.........这里部分代码省略.........

        dest = args[0]
        src = args[1]
        index = self.get_link_index(args[2])

        dest_type = self.check_ip_address(dest)
        src_type = self.check_ip_address(src)

        if dest == "default" and src_type == self.IP:
            # default ip
            self.iproute.route("add", oif=index, gateway=src, proto=rtprotos["RTPROT_BOOT"])
        elif dest == "default" and src == "none":
            # default none
            self.iproute.route("add", oif=index, gateway=src, proto=rtprotos["RTPROT_BOOT"], dst_len=0, scope=rtscopes["RT_SCOPE_LINK"])
        elif dest_type == self.IP_MASK and src_type == self.IP:
            # ip/mask ip
            self.iproute.route("add", oif=index, gateway=src, dst=dest, proto=rtprotos["RTPROT_BOOT"])
        elif dest_type == self.IP_MASK and src == "none":
            # ip/mask none
            self.iproute.route("add", oif=index, dst=dest, proto=rtprotos["RTPROT_BOOT"], scope=rtscopes["RT_SCOPE_LINK"])
        elif dest_type == self.IP and src_type == self.IP:
            # ip ip
            self.iproute.route("add", oif=index, gateway=src, dst=dest, proto=rtprotos["RTPROT_BOOT"], dst_len=32)
        elif dest_type == self.IP and src == "none":
            # ip none
            self.iproute.route("add", oif=index, dst=dest, proto=rtprotos["RTPROT_BOOT"], dst_len=32, scope=rtscopes["RT_SCOPE_LINK"])
        else:
            raise TypeError()

    def cmd_show_link(self, args=[]):
        if len(args) == 0:
            self.cmd_show_brief_info()
        elif args[0] == "all":
            for link in self.iproute.get_links():
                self.cmd_show_link_info(link.get_attr("IFLA_IFNAME"))
        else:
            self.cmd_show_link_info(args[0])

    def cmd_show_brief_info(self):
        self.print_output_boarder(True)
        self.print_ip_brief("Index", "Interface", "State", "IP")
        self.print_output_boarder(False)

        for link in self.iproute.get_links():
            index = link["index"]
            ip = self.iproute.get_addr(index=index)

            if len(ip) == 0:
                self.print_ip_brief(str(index), link.get_attr("IFLA_IFNAME"), link.get_attr("IFLA_OPERSTATE"), "None")
                continue

            for idx, address in enumerate(ip):
                index_format = "%s.%s" % (index, idx)
                interface = link.get_attr("IFLA_IFNAME") if idx == 0 else ""
                state = link.get_attr("IFLA_OPERSTATE") if idx == 0 else ""

                self.print_ip_brief(index_format, interface, state, address.get_attr("IFA_ADDRESS"))

        self.print_output_boarder(True)

    def cmd_show_link_info(self, link_name):
        index = self.get_link_index(link_name)
        link = self.iproute.get_links(index)[0]

        self.print_output_boarder(True)
        self.print_key_value("Index", link["index"])
开发者ID:IPOT,项目名称:PTYSH,代码行数:70,代码来源:network_module.py

示例13: TestIPRoute

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]

#.........这里部分代码省略.........

    def test_create_ipvlan_l3(self):
        return self._create_ipvlan('IPVLAN_MODE_L3')

    @skip_if_not_supported
    def _create(self, kind, **kwarg):
        name = uifname()
        self.ip.link('add', ifname=name, kind=kind, **kwarg)
        devs = self.ip.link_lookup(ifname=name)
        assert devs
        self.ifaces.extend(devs)
        return (name, devs[0])

    def test_create_dummy(self):
        require_user('root')
        self._create('dummy')

    def test_create_bond(self):
        require_user('root')
        self._create('bond')

    def test_create_bridge(self):
        require_user('root')
        self._create('bridge')

    def test_create_team(self):
        require_user('root')
        self._create('team')

    def test_ntables(self):
        setA = set(filter(lambda x: x is not None,
                          [x.get_attr('NDTA_PARMS').get_attr('NDTPA_IFINDEX')
                           for x in self.ip.get_ntables()]))
        setB = set([x['index'] for x in self.ip.get_links()])
        assert setA == setB

    def test_fdb_vxlan(self):
        require_kernel(4, 4)
        require_user('root')
        # create dummy
        (dn, dx) = self._create('dummy')
        # create vxlan on it
        (vn, vx) = self._create('vxlan', vxlan_link=dx, vxlan_id=500)
        # create FDB record
        l2 = '00:11:22:33:44:55'
        self.ip.fdb('add', lladdr=l2, ifindex=vx,
                    vni=600, port=5678, dst='172.16.40.40')
        # dump
        r = self.ip.fdb('dump', ifindex=vx, lladdr=l2)
        assert len(r) == 1
        assert r[0]['ifindex'] == vx
        assert r[0].get_attr('NDA_LLADDR') == l2
        assert r[0].get_attr('NDA_DST') == '172.16.40.40'
        assert r[0].get_attr('NDA_PORT') == 5678
        assert r[0].get_attr('NDA_VNI') == 600

    def test_fdb_bridge_simple(self):
        require_kernel(4, 4)
        require_user('root')
        # create bridge
        (bn, bx) = self._create('bridge')
        # create FDB record
        l2 = '00:11:22:33:44:55'
        self.ip.fdb('add', lladdr=l2, ifindex=bx)
        # dump FDB
        r = self.ip.fdb('dump', ifindex=bx, lladdr=l2)
开发者ID:pwns4cash,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py

示例14: TestData

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]
class TestData(object):

    def setup(self):
        create_link('dummyX', 'dummy')
        self.ip = IPRoute()
        self.dev = self.ip.link_lookup(ifname='dummyX')

    def teardown(self):
        self.ip.release()
        remove_link('dummyX')
        remove_link('bala')

    def test_nla_operators(self):
        require_user('root')
        dev = self.dev[0]
        self.ip.addr('add', dev, address='172.16.0.1', mask=24)
        self.ip.addr('add', dev, address='172.16.0.2', mask=24)
        r = [x for x in self.ip.get_addr() if x['index'] == dev]
        complement = r[0] - r[1]
        intersection = r[0] & r[1]

        assert complement.get_attr('IFA_ADDRESS') == '172.16.0.1'
        assert complement.get_attr('IFA_LABEL') is None
        assert complement['prefixlen'] == 0
        assert complement['index'] == 0

        assert intersection.get_attr('IFA_ADDRESS') is None
        assert intersection.get_attr('IFA_LABEL') == 'dummyX'
        assert intersection['prefixlen'] == 24
        assert intersection['index'] == dev

    def test_add_addr(self):
        require_user('root')
        dev = self.dev[0]
        self.ip.addr('add', dev, address='172.16.0.1', mask=24)
        assert '172.16.0.1/24' in get_ip_addr()

    def test_remove_link(self):
        require_user('root')
        create_link('bala', 'dummy')
        dev = self.ip.link_lookup(ifname='bala')[0]
        try:
            self.ip.link_remove(dev)
        except NetlinkError:
            pass
        assert len(self.ip.link_lookup(ifname='bala')) == 0

    def test_get_route(self):
        if not self.ip.get_default_routes(table=254):
            return
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst='8.8.8.8',
                                 table=254)
        assert len(rts) > 0

    def test_route_table_2048(self):
        require_user('root')
        create_link('bala', 'dummy')
        dev = self.ip.link_lookup(ifname='bala')[0]
        self.ip.link('set', index=dev, state='up')
        self.ip.addr('add', dev, address='172.16.0.2', mask=24)
        self.ip.route('add',
                      prefix='172.16.1.0',
                      mask=24,
                      gateway='172.16.0.1',
                      table=2048)
        assert grep('ip route show table 2048',
                    pattern='172.16.1.0/24.*172.16.0.1')
        remove_link('bala')

    def test_updown_link(self):
        require_user('root')
        dev = self.dev[0]
        assert not (self.ip.get_links(dev)[0]['flags'] & 1)
        try:
            self.ip.link_up(dev)
        except NetlinkError:
            pass
        assert self.ip.get_links(dev)[0]['flags'] & 1
        try:
            self.ip.link_down(dev)
        except NetlinkError:
            pass
        assert not (self.ip.get_links(dev)[0]['flags'] & 1)

    def test_callbacks_positive(self):
        require_user('root')
        dev = self.dev[0]

        self.cb_counter = 0
        self.ip.register_callback(_callback,
                                  lambda e, x: x.get('index', None) == dev,
                                  (self, ))
        self.test_updown_link()
        assert self.cb_counter > 0
        self.ip.unregister_callback(_callback)

    def test_callbacks_negative(self):
        require_user('root')

#.........这里部分代码省略.........
开发者ID:hegusung,项目名称:pyroute2,代码行数:103,代码来源:test_ipr.py

示例15: TestIPRoute

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_links [as 别名]

#.........这里部分代码省略.........
    def test_flush_rules(self):
        require_user('root')
        ifaddr1 = self.ifaddr(0)
        ifaddr2 = self.ifaddr(1)
        init = len(self.ip.get_rules(family=socket.AF_INET))
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 0
        self.ip.rule('add', table=10, priority=110)
        self.ip.rule('add', table=15, priority=150, action='FR_ACT_PROHIBIT')
        self.ip.rule('add', table=20, priority=200, src=ifaddr1)
        self.ip.rule('add', table=25, priority=250, dst=ifaddr2)
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 4
        assert len(self.ip.get_rules(src=ifaddr1)) == 1
        assert len(self.ip.get_rules(dst=ifaddr2)) == 1
        self.ip.flush_rules(family=socket.AF_INET,
                            priority=lambda x: 100 < x < 500)
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 0
        assert len(self.ip.get_rules(src=ifaddr1)) == 0
        assert len(self.ip.get_rules(dst=ifaddr2)) == 0
        assert len(self.ip.get_rules(family=socket.AF_INET)) == init

    def test_rules_deprecated(self):
        require_user('root')
        init = len(self.ip.get_rules(family=socket.AF_INET))
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 0
        self.ip.rule('add', 10, 110)
        self.ip.rule('add', 15, 150, 'FR_ACT_PROHIBIT')
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 2
        self.ip.flush_rules(family=socket.AF_INET,
                            priority=lambda x: 100 < x < 500)
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 0
        assert len(self.ip.get_rules(family=socket.AF_INET)) == init

    def test_match_callable(self):
        assert len(self.ip.get_links(match=partial(lambda x: x))) > 0

    def test_addr_filter(self):
        require_user('root')
        ifaddr_brd = self.ifaddr()
        ifaddr1 = self.ifaddr()
        ifaddr2 = self.ifaddr()
        self.ip.addr('add',
                     index=self.ifaces[0],
                     address=ifaddr1,
                     prefixlen=24,
                     broadcast=ifaddr_brd)
        self.ip.addr('add',
                     index=self.ifaces[0],
                     address=ifaddr2,
                     prefixlen=24,
                     broadcast=ifaddr_brd)
        assert len(self.ip.get_addr(index=self.ifaces[0])) == 2
        assert len(self.ip.get_addr(address=ifaddr1)) == 1
        assert len(self.ip.get_addr(broadcast=ifaddr_brd)) == 2
        assert len(self.ip.get_addr(match=lambda x: x['index'] ==
                                    self.ifaces[0])) == 2

    @skip_if_not_supported
    def _create_ipvlan(self, smode):
        require_user('root')
        master = self.uifname()
        ipvlan = self.uifname()
        # create the master link
        self.ip.link('add', ifname=master, kind='dummy')
        midx = self.ip.link_lookup(ifname=master)[0]
        # check modes
        # maybe move modes dict somewhere else?
开发者ID:svinota,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py


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