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


Python IPRoute.get_routes方法代码示例

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


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

示例1: set_net

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_routes [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

示例2: TestIPRoute

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

#.........这里部分代码省略.........
            self.ip.addr('add', 1, address='172.16.0.1', mask=24)
        except NetlinkError as e:
            if e.code != 1:  # Operation not permitted
                raise
        finally:
            try:
                self.ip.addr('delete', 1, address='172.16.0.1', mask=24)
            except:
                pass

    def test_fail_no_such_device(self):
        require_user('root')
        dev = sorted([i['index'] for i in self.ip.get_links()])[-1] + 10
        try:
            self.ip.addr('add',
                         dev,
                         address='172.16.0.1',
                         mask=24)
        except NetlinkError as e:
            if e.code != 19:  # No such device
                raise

    def test_remove_link(self):
        require_user('root')
        try:
            self.ip.link_remove(self.ifaces[0])
        except NetlinkError:
            pass
        assert len(self.ip.link_lookup(ifname=self.dev)) == 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_flush_routes(self):
        require_user('root')
        self.ip.link('set', index=self.ifaces[0], state='up')
        self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
        self.ip.route('add',
                      prefix='172.16.1.0',
                      mask=24,
                      gateway='172.16.0.1',
                      table=100)
        self.ip.route('add',
                      prefix='172.16.2.0',
                      mask=24,
                      gateway='172.16.0.1',
                      table=100)

        assert grep('ip route show table 100',
                    pattern='172.16.1.0/24.*172.16.0.1')
        assert grep('ip route show table 100',
                    pattern='172.16.2.0/24.*172.16.0.1')

        self.ip.flush_routes(table=100)

        assert not grep('ip route show table 100',
                        pattern='172.16.1.0/24.*172.16.0.1')
        assert not grep('ip route show table 100',
                        pattern='172.16.2.0/24.*172.16.0.1')

    def test_route_table_2048(self):
开发者ID:jazzmes,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py

示例3: TestIPRoute

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

#.........这里部分代码省略.........
        assert grep('ip ro', pattern='%s/24.*127.0.0.1' % naddr)
        try:
            self.ip.route('del',
                          dst='%s/24' % naddr,
                          gateway='127.0.0.1',
                          proto=fake)
        except NetlinkError:
            pass
        self.ip.route('del',
                      dst='%s/24' % naddr,
                      gateway='127.0.0.1',
                      proto=proto)
        assert not grep('ip ro', pattern='%s/24.*127.0.0.1' % naddr)

    def test_route_proto_static(self):
        return self._test_route_proto('static', 'boot', 'proto static')

    def test_route_proto_static_num(self):
        return self._test_route_proto(4, 3, 'proto static')

    def test_route_proto_boot(self):
        return self._test_route_proto('boot', 4)

    def test_route_proto_boot_num(self):
        return self._test_route_proto(3, 'static')

    def test_route_oif_as_iterable(self):
        require_user('root')
        naddr = str(self.ipnets[1].network)
        spec = {'dst': naddr,
                'dst_len': 24,
                'oif': (1, )}
        self.ip.route('add', **spec)
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst=naddr)
        self.ip.route('del', **spec)
        assert len(rts) == 1
        assert rts[0].get_attr('RTA_OIF') == 1

    def test_route_get_target(self):
        if not self.ip.get_default_routes(table=254):
            raise SkipTest('no default IPv4 routes')
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst='8.8.8.8',
                                 table=254)
        assert len(rts) > 0

    def test_route_get_target_default_ipv4(self):
        rts = self.ip.get_routes(dst='127.0.0.1')
        assert len(rts) > 0

    def test_route_get_target_default_ipv6(self):
        rts = self.ip.get_routes(dst='::1')
        assert len(rts) > 0

    def test_route_get_by_spec(self):
        require_user('root')
        ifaddr1 = self.ifaddr(0)
        ifaddr2 = self.ifaddr(1)
        self.ip.link('set', index=self.ifaces[0], state='up')
        self.ip.addr('add', index=self.ifaces[0],
                     address=ifaddr1, mask=24)
        self.ip.addr('add', index=self.ifaces[0],
                     address=ifaddr2, mask=24)
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst=lambda x: x in (ifaddr1,
开发者ID:svinota,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py

示例4: bench

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_routes [as 别名]
def bench(args):
    config_dir = '{0}/{1}'.format(args.dir, args.bench_name)
    brname = args.bench_name + '-br'

    ip = IPRoute()
    ctn_intfs = flatten((l.get_attr('IFLA_IFNAME') for l in ip.get_links() if l.get_attr('IFLA_MASTER') == br) for br in ip.link_lookup(ifname=brname))

    if not args.repeat:
        # currently ctn name is same as ctn intf
        # TODO support proper mapping between ctn name and intf name
        for ctn in ctn_intfs:
            dckr.remove_container(ctn, force=True) if ctn_exists(ctn) else None

        if os.path.exists(config_dir):
            shutil.rmtree(config_dir)
    else:
        for ctn in ctn_intfs:
            if ctn != 'tester':
                dckr.remove_container(ctn, force=True) if ctn_exists(ctn) else None

    if args.file:
        with open(args.file) as f:
            conf = yaml.load(f)
    else:
        conf = gen_conf(args)
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)
        with open('{0}/scenario.yaml'.format(config_dir), 'w') as f:
            f.write(yaml.dump(conf))

    if len(conf['tester']) > gc_thresh3():
        print 'gc_thresh3({0}) is lower than the number of peer({1})'.format(gc_thresh3(), len(conf['tester']))
        print 'type next to increase the value'
        print '$ echo 16384 | sudo tee /proc/sys/net/ipv4/neigh/default/gc_thresh3'

    if args.target == 'gobgp':
        target = GoBGP
    elif args.target == 'bird':
        target = BIRD
    elif args.target == 'quagga':
        target = Quagga

    is_remote = True if 'remote' in conf['target'] and conf['target']['remote'] else False

    if is_remote:
        r = ip.get_routes(dst=conf['target']['local-address'].split('/')[0], family=AF_INET)
        if len(r) == 0:
            print 'no route to remote target {0}'.format(conf['target']['local-address'])
            sys.exit(1)

        idx = [t[1] for t in r[0]['attrs'] if t[0] == 'RTA_OIF'][0]
        intf = ip.get_links(idx)[0]

        if intf.get_attr('IFLA_MASTER') not in ip.link_lookup(ifname=brname):
            br = ip.link_lookup(ifname=brname)
            if len(br) == 0:
                ip.link_create(ifname=brname, kind='bridge')
                br = ip.link_lookup(ifname=brname)
            br = br[0]
            ip.link('set', index=idx, master=br)
    else:
        print 'run', args.target
        if args.image:
            target = target(args.target, '{0}/{1}'.format(config_dir, args.target), image=args.image)
        else:
            target = target(args.target, '{0}/{1}'.format(config_dir, args.target))
        target.run(conf, brname)

    print 'run monitor'
    m = Monitor('monitor', config_dir+'/monitor')
    m.run(conf, brname)

    time.sleep(1)

    print 'waiting bgp connection between {0} and monitor'.format(args.target)
    m.wait_established(conf['target']['local-address'].split('/')[0])

    if not args.repeat:
        print 'run tester'
        t = Tester('tester', config_dir+'/tester')
        t.run(conf, brname)

    start = datetime.datetime.now()

    q = Queue()

    m.stats(q)
    if not is_remote:
        target.stats(q)

    def mem_human(v):
        if v > 1000 * 1000 * 1000:
            return '{0:.2f}GB'.format(float(v) / (1000 * 1000 * 1000))
        elif v > 1000 * 1000:
            return '{0:.2f}MB'.format(float(v) / (1000 * 1000))
        elif v > 1000:
            return '{0:.2f}KB'.format(float(v) / 1000)
        else:
            return '{0:.2f}B'.format(float(v))

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

示例5: TestIPRoute

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

#.........这里部分代码省略.........
            self.ip.addr('add', 1, address='172.16.0.1', mask=24)
        except NetlinkError as e:
            if e.code != errno.EPERM:  # Operation not permitted
                raise
        finally:
            try:
                self.ip.addr('delete', 1, address='172.16.0.1', mask=24)
            except:
                pass

    def test_fail_no_such_device(self):
        require_user('root')
        dev = sorted([i['index'] for i in self.ip.get_links()])[-1] + 10
        try:
            self.ip.addr('add',
                         dev,
                         address='172.16.0.1',
                         mask=24)
        except NetlinkError as e:
            if e.code != errno.ENODEV:  # No such device
                raise

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

    def test_route_get_target(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_get_by_spec(self):
        self.ip.link('set', index=self.ifaces[0], state='up')
        self.ip.addr('add', index=self.ifaces[0],
                     address='172.16.60.1', mask=24)
        self.ip.addr('add', index=self.ifaces[0],
                     address='172.16.61.1', mask=24)
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst=lambda x: x in ('172.16.60.0',
                                                     '172.16.61.0'))
        assert len(rts) == 4

    def test_route_multipath(self):
        require_user('root')
        self.ip.route('add',
                      dst='172.16.241.0',
                      mask=24,
                      multipath=[{'hops': 20,
                                  'ifindex': 1,
                                  'attrs': [['RTA_GATEWAY', '127.0.0.2']]},
                                 {'hops': 30,
                                  'ifindex': 1,
                                  'attrs': [['RTA_GATEWAY', '127.0.0.3']]}])
        assert grep('ip route show', pattern='172.16.241.0/24')
        assert grep('ip route show', pattern='nexthop.*127.0.0.2.*weight 21')
        assert grep('ip route show', pattern='nexthop.*127.0.0.3.*weight 31')
        self.ip.route('del', dst='172.16.241.0', mask=24)

    def test_route_multipath_helper(self):
开发者ID:thezeep,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py

示例6: TestData

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

#.........这里部分代码省略.........
    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_route(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')
        assert grep('ip route show', 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')

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

    def test_rename_link(self):
        require_user('root')
        dev = self.dev[0]
        try:
            self.ip.link_rename(dev, 'bala')
        except NetlinkError:
            pass
        assert len(self.ip.link_lookup(ifname='bala')) == 1
        try:
            self.ip.link_rename(dev, 'dummyX')
        except NetlinkError:
            pass
        assert len(self.ip.link_lookup(ifname='dummyX')) == 1

    def test_rules(self):
        assert len(get_ip_rules('-4')) == \
            len(self.ip.get_rules(socket.AF_INET))
        assert len(get_ip_rules('-6')) == \
            len(self.ip.get_rules(socket.AF_INET6))

    def test_addr(self):
        assert len(get_ip_addr()) == len(self.ip.get_addr())

    def test_links(self):
        assert len(get_ip_link()) == len(self.ip.get_links())

    def test_one_link(self):
        lo = self.ip.get_links(1)[0]
        assert lo.get_attr('IFLA_IFNAME') == 'lo'

    def test_routes(self):
        assert len(get_ip_route()) == \
            len(self.ip.get_routes(family=socket.AF_INET, table=255))
开发者ID:chantra,项目名称:pyroute2,代码行数:104,代码来源:test_ipr.py

示例7: network_module

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

#.........这里部分代码省略.........
        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"])
        self.print_key_value("Name", link.get_attr("IFLA_IFNAME"))
        self.print_key_value("Mac address", link.get_attr("IFLA_ADDRESS"))
        self.print_key_value("Broadcast", link.get_attr("IFLA_BROADCAST"))
        self.print_key_value("MTU", link.get_attr("IFLA_MTU"))
        self.print_key_value("Status", link.get_attr("IFLA_OPERSTATE"))
        self.print_key_value("Promiscuity", link.get_attr("IFLA_PROMISCUITY"))

        stats = link.get_attr("IFLA_STATS64")
        self.print_key_value("multicast", stats["multicast"])
        self.print_key_value("collisions", stats["collisions"])

        for ip in self.iproute.get_addr(index=index):
            self.print_output_subject("IP")
            self.print_key_value("- IP", ip.get_attr("IFA_ADDRESS"))
            self.print_key_value("- Broadcast IP", ip.get_attr("IFA_BROADCAST"))
            self.print_key_value("- Subnet", ip["prefixlen"])
            self.print_output_boarder(False)

        self.print_output_subject("RX")
        self.print_key_value("- rx_packets", stats["rx_packets"])
        self.print_key_value("- rx_bytes", stats["rx_bytes"])
        self.print_key_value("- rx_dropped", stats["rx_dropped"])
        self.print_key_value("- rx_errors", stats["rx_errors"])
        self.print_key_value("- rx_compressed", stats["rx_compressed"])
        self.print_key_value("- rx_over_errors", stats["rx_over_errors"])
        self.print_key_value("- rx_crc_errors", stats["rx_crc_errors"])
        self.print_key_value("- rx_length_errors", stats["rx_length_errors"])
        self.print_key_value("- rx_fifo_errors", stats["rx_fifo_errors"])
        self.print_key_value("- rx_missed_errors", stats["rx_missed_errors"])
        self.print_key_value("- rx_frame_errors", stats["rx_frame_errors"])
        self.print_output_boarder(False)

        self.print_output_subject("TX")
        self.print_key_value("- tx_packets", stats["tx_packets"])
        self.print_key_value("- tx_bytes", stats["tx_bytes"])
        self.print_key_value("- tx_dropped", stats["tx_dropped"])
        self.print_key_value("- tx_errors", stats["tx_errors"])
        self.print_key_value("- tx_compressed", stats["tx_compressed"])
        self.print_key_value("- tx_heartbeat_errors", stats["tx_heartbeat_errors"])
        self.print_key_value("- tx_aborted_errors", stats["tx_aborted_errors"])
        self.print_key_value("- tx_window_errors", stats["tx_window_errors"])
        self.print_key_value("- tx_fifo_errors", stats["tx_fifo_errors"])
        self.print_key_value("- tx_carrier_errors", stats["tx_carrier_errors"])
        self.print_output_boarder(False)

        self.print_output_boarder(True)

    def cmd_show_route(self):
        self.print_output_boarder(True)
        self.print_route_table("Index", "Destination", "Gateway", "Mask", "Interface")
        self.print_output_boarder(False)

        for index, route in enumerate(self.iproute.get_routes(table=254)):
            if route.get_attr("RTA_DST", None) is None and route["dst_len"] == 0:
                destination = "default"
                gateway = route.get_attrs("RTA_GATEWAY")[0]
            else:
                destination = route.get_attrs("RTA_DST")[0]
                gateway = "0.0.0.0"

            interface_index = route.get_attrs("RTA_OIF")[0]
            interface = self.iproute.get_links(interface_index)[0].get_attrs("IFLA_IFNAME")[0]
            self.print_route_table(str(index), destination, gateway, str(route["dst_len"]), interface)
        self.print_output_boarder(True)
开发者ID:IPOT,项目名称:PTYSH,代码行数:104,代码来源:network_module.py

示例8: TestData

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_routes [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

示例9: TestIPRoute

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

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

        assert grep('ip ro', pattern='172.16.3.0/24.*127.0.0.1')
        try:
            self.ip.route('del',
                          dst='172.16.3.0/24',
                          gateway='127.0.0.1',
                          proto=fake)
        except NetlinkError:
            pass
        self.ip.route('del',
                      dst='172.16.3.0/24',
                      gateway='127.0.0.1',
                      proto=proto)
        assert not grep('ip ro', pattern='172.16.3.0/24.*127.0.0.1')

    def test_route_proto_static(self):
        return self._test_route_proto('static', 'boot', 'proto static')

    def test_route_proto_static_num(self):
        return self._test_route_proto(4, 3, 'proto static')

    def test_route_proto_boot(self):
        return self._test_route_proto('boot', 4)

    def test_route_proto_boot_num(self):
        return self._test_route_proto(3, 'static')

    def test_route_oif_as_iterable(self):
        require_user('root')
        spec = {'dst': '172.16.0.0',
                'dst_len': 24,
                'oif': (1, )}
        self.ip.route('add', **spec)
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst='172.16.0.0')
        self.ip.route('del', **spec)
        assert len(rts) == 1
        assert rts[0].get_attr('RTA_OIF') == 1

    def test_route_get_target(self):
        if not self.ip.get_default_routes(table=254):
            raise SkipTest('no default IPv4 routes')
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst='8.8.8.8',
                                 table=254)
        assert len(rts) > 0

    def test_route_get_target_default_ipv4(self):
        rts = self.ip.get_routes(dst='127.0.0.1')
        assert len(rts) > 0

    def test_route_get_target_default_ipv6(self):
        rts = self.ip.get_routes(dst='::1')
        assert len(rts) > 0

    def test_route_get_by_spec(self):
        require_user('root')
        self.ip.link('set', index=self.ifaces[0], state='up')
        self.ip.addr('add', index=self.ifaces[0],
                     address='172.16.60.1', mask=24)
        self.ip.addr('add', index=self.ifaces[0],
                     address='172.16.61.1', mask=24)
        rts = self.ip.get_routes(family=socket.AF_INET,
                                 dst=lambda x: x in ('172.16.60.0',
                                                     '172.16.61.0'))
        assert len(rts) == 4
开发者ID:pwns4cash,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py

示例10: main

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_routes [as 别名]
def main(argv):
    if (len(argv) !=  2):
        print('Usage: python pvdtest_veth.py PVD_ID')
        print('PVD_ID := name of the interface that contains PvD-related network configuration')
        sys.exit()

    # Get user-entered PVD ID
    pvdId = sys.argv[1]
    
    # Create IPRoute object for manipulation with a default network namespace
    ipMain = IPRoute()

    # Create a PvD-related network namespace
    pvdNetnsName = getPvdNetnsName(pvdId);
    if (pvdNetnsName in netns.listnetns()):
        netns.remove(pvdNetnsName)
    netns.create(pvdNetnsName)

    # Create IPRoute object for manipulation with a PvD-related network namespace
    netns.setns(pvdNetnsName)
    ipPvd = IPRoute()

    # Activate loopback interface in a PvD-related network namespace
    loIndex = ipPvd.link_lookup(ifname='lo')[0]
    ipPvd.link_up(loIndex)

    # Get addresses from a PvD-related network interface
    pvdIfIndex = ipMain.link_lookup(ifname=getPvdIfName(pvdId))[0]
    pvdAddresses = ipMain.get_addr(index=pvdIfIndex)

    # Get current routes
    pvdRoutes = ipMain.get_routes()

    # Create bridge
    bridge = getPvdBridgeName(pvdId)
    ipMain.link_create(ifname=bridge, kind='bridge')

    # Create veth interface
    (veth0, veth1) = getPvdVethNames(pvdId)
    ipMain.link_create(ifname=veth0, kind='veth', peer=veth1)

    # Move one end of the veth interafce to a PvD-related network namespace
    veth1Index = ipMain.link_lookup(ifname=veth1)[0]
    ipMain.link('set', index=veth1Index, net_ns_fd=pvdNetnsName)

    # Shut down and remove addresses from the PvD interface before adding it to the bridge
    ipMain.link_down(pvdIfIndex)
    ipMain.flush_addr(pvdIfIndex)

    # Make a bridge between PvD interface and one end of veth interface
    veth0Index = ipMain.link_lookup(ifname=veth0)[0]
    bridgeIndex = ipMain.link_lookup(ifname=bridge)[0]
    ipMain.link('set', index=veth0Index, master=bridgeIndex)
    ipMain.link('set', index=pvdIfIndex, master=bridgeIndex)

    # Activate bridge and connected interfaces
    ipMain.link_up(pvdIfIndex)
    ipMain.link_up(veth0Index)
    ipMain.link_up(bridgeIndex)
    ipPvd.link_up(veth1Index)

    # Configure bridge and another end of the veth interface with PvD-related network parameters + add routes
    ipMain.flush_routes()
    ipPvd.flush_routes()
    for address in pvdAddresses:
        ipAddress = broadcastAddress = netmask = addrFamily = None
        for attr in address['attrs']:
            if attr[0] == 'IFA_ADDRESS':
                ipAddress = attr[1]
            if attr[0] == 'IFA_BROADCAST':
                broadcastAddress = attr[1]
        netmask = address['prefixlen']
        addrFamily = address['family']
        # Configure bridge
        try:
            ipMain.addr('add', index=bridgeIndex, family=addrFamily, address=ipAddress, broadcast=broadcastAddress, mask=netmask)
        except:
            pass
        # Configure veth
        try:
            ipPvd.addr('add', index=veth1Index, family=addrFamily, address=ipAddress, broadcast=broadcastAddress, mask=netmask)
        except:
            pass
        # Configure routes
        # Some routes are added during interface IP address/netmask configuration, skip them if already there
        ipNetwork = IPNetwork(ipAddress + '/' + str(netmask))
        try:
            ipMain.route('add', dst=str(ipNetwork.network), mask=netmask, oif=bridgeIndex, src=ipAddress, rtproto='RTPROT_STATIC', rtscope='RT_SCOPE_LINK')
        except:
            pass
        try:
            ipPvd.route('add', dst=str(ipNetwork.network), mask=netmask, oif=veth1Index, src=ipAddress, rtproto='RTPROT_STATIC', rtscope='RT_SCOPE_LINK')
        except:
            pass

    # Fing gateway(s) and add default routes
    defGateways = []
    for route in pvdRoutes:
        for attr in route['attrs']:
            if (attr[0] == 'RTA_GATEWAY' and attr[1] not in defGateways):
#.........这里部分代码省略.........
开发者ID:dskvorc,项目名称:misc,代码行数:103,代码来源:pvdtest_veth.py


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