本文整理汇总了Python中pyroute2.IPRoute.get_addr方法的典型用法代码示例。如果您正苦于以下问题:Python IPRoute.get_addr方法的具体用法?Python IPRoute.get_addr怎么用?Python IPRoute.get_addr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyroute2.IPRoute
的用法示例。
在下文中一共展示了IPRoute.get_addr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestMisc
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class TestMisc(object):
def setup(self):
self.ip = IPRoute()
def teardown(self):
self.ip.release()
def test_addrpool_expand(self):
# see coverage
for i in range(100):
self.ip.get_addr()
示例2: set_net
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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)
示例3: scan_netdevs
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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
示例4: LoopBackAddress
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class LoopBackAddress(object):
def __init__(self, logger, config):
self.config = config
self._label = self.config.get("balancer.agent.plugins.loopback", "label")
self._prefix = self.config.getint("balancer.agent.plugins.loopback", "prefix")
self._ip = IPRoute()
self._idx = self._ip.link_lookup(ifname="lo")[0]
self.logger = logger
@property
def configured_ips(self):
ips = set()
for link in self._ip.get_addr(index=self._idx):
if not "attrs" in link:
continue
interface = None
ip = None
for key, value in link["attrs"]:
if key == "IFA_ADDRESS":
ip = value
elif key == "IFA_LABEL":
interface = value
elif interface == self._label and ip not in ["127.0.0.1", None]:
ips.add(ip)
return ips
def close(self):
if self._ip:
self._ip.close()
def __disable__(self, ip):
self.logger("Disabling {}/{} on {}".format(ip, self._prefix, self._label))
self._ip.addr("del", index=self._idx, address=ip, prefixlen=self._prefix, label=self._label)
def __enable__(self, ip):
self.logger("Enabling {}/{} on {}".format(ip, self._prefix, self._label))
self._ip.addr("add", index=self._idx, address=ip, prefixlen=self._prefix, label=self._label)
def apply(self, frontends):
configured_ips = self.configured_ips
ips = set()
for frontend, ips_and_ports in frontends.items():
for ip, port in ips_and_ports:
ips.add(ip)
to_disabled = configured_ips.difference(ips)
to_enabled = ips.difference(configured_ips)
for ip in to_disabled:
self.__disable__(ip)
for ip in to_enabled:
self.__enable__(ip)
示例5: TestMisc
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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
示例6: TestMisc
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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
示例7: main
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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=(',', ':'))
示例8: VrrpPlugin
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class VrrpPlugin(base.Base):
def __init__(self, *args, **kwargs):
super(VrrpPlugin, self).__init__(*args, **kwargs)
self.plugin = NAME
self.ip_addresses = []
self.ipr = IPRoute()
def config_callback(self, conf):
"""Parse the plugin configuration.
Example:
<Module "collectd_vrrp">
<IPAddress>
address "172.16.10.254"
label "Foo"
</IPAddress>
<IPAddress>
address "172.16.10.253"
</IPAddress>
</Module>
"""
super(VrrpPlugin, self).config_callback(conf)
for node in conf.children:
if node.key == 'IPAddress':
item = {}
for child_node in node.children:
if child_node.key not in ('address', 'label'):
continue
item[child_node.key] = child_node.values[0]
if 'address' not in item:
self.logger.error("vrrp: Missing 'address' parameter")
self.ip_addresses.append(item)
if len(self.ip_addresses) == 0:
self.logger.error("vrrp: Missing 'IPAddress' parameter")
def itermetrics(self):
local_addresses = [i.get_attr('IFA_LOCAL') for i in
self.ipr.get_addr(family=socket.AF_INET)]
for ip_address in self.ip_addresses:
v = 1 if ip_address['address'] in local_addresses else 0
data = {'values': v, 'meta': {'ip_address': ip_address['address']}}
if 'label' in ip_address:
data['meta']['label'] = ip_address['label']
yield data
示例9: TestData
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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))
示例10: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class TestIPRoute(object):
def setup(self):
self.ip = IPRoute()
try:
self.ifaces = []
self.dev, idx = self.create()
except IndexError:
pass
def create(self, kind='dummy'):
name = uifname()
create_link(name, kind=kind)
idx = self.ip.link_lookup(ifname=name)[0]
self.ifaces.append(idx)
return (name, idx)
def teardown(self):
if hasattr(self, 'ifaces'):
for dev in self.ifaces:
try:
self.ip.link('delete', index=dev)
except:
pass
self.ip.close()
def _test_nla_operators(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
r = [x for x in self.ip.get_addr() if x['index'] == self.ifaces[0]]
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') == self.dev
assert intersection['prefixlen'] == 24
assert intersection['index'] == self.ifaces[0]
def test_addr_add(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
assert '172.16.0.1/24' in get_ip_addr()
def test_vlan_filter_dump(self):
require_user('root')
(an, ax) = self.create('bridge')
(bn, bx) = self.create('bridge')
self.ip.link('set', index=ax, state='up')
self.ip.link('set', index=bx, state='up')
assert len(self.ip.get_vlans()) >= 2
for name in (an, bn):
assert len(self.ip.get_vlans(ifname=name)) == 1
assert (self
.ip
.get_vlans(ifname=name)[0]
.get_attr('IFLA_IFNAME')) == name
assert (self
.ip
.get_vlans(ifname=name)[0]
.get_nested('IFLA_AF_SPEC',
'IFLA_BRIDGE_VLAN_INFO'))['vid'] == 1
def test_vlan_filter_add(self):
require_user('root')
(bn, bx) = self.create('bridge')
(sn, sx) = self.create('dummy')
self.ip.link('set', index=sx, master=bx)
assert not grep('bridge vlan show', pattern='567')
self.ip.vlan_filter('add', index=sx, vlan_info={'vid': 567})
assert grep('bridge vlan show', pattern='567')
self.ip.vlan_filter('del', index=sx, vlan_info={'vid': 567})
assert not grep('bridge vlan show', pattern='567')
def test_vlan_filter_add_raw(self):
require_user('root')
(bn, bx) = self.create('bridge')
(sn, sx) = self.create('dummy')
self.ip.link('set', index=sx, master=bx)
assert not grep('bridge vlan show', pattern='567')
self.ip.vlan_filter('add', index=sx,
af_spec={'attrs': [['IFLA_BRIDGE_VLAN_INFO',
{'vid': 567}]]})
assert grep('bridge vlan show', pattern='567')
self.ip.vlan_filter('del', index=sx,
af_spec={'attrs': [['IFLA_BRIDGE_VLAN_INFO',
{'vid': 567}]]})
assert not grep('bridge vlan show', pattern='567')
def test_local_add(self):
require_user('root')
self.ip.addr('add', self.ifaces[0],
address='172.16.0.2',
local='172.16.0.1',
mask=24)
#.........这里部分代码省略.........
示例11: IPDB
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
from pprint import pprint
from pyroute2 import IPRoute
from pyroute2 import IPDB
from pyroute2.common import uifname
# high-level interface
ipdb = IPDB()
interface = ipdb.create(ifname=uifname(), kind='dummy').\
commit().\
add_ip('172.16.0.1/24').\
add_ip('172.16.0.2/24').\
commit()
# low-level interface just to get raw messages
ip = IPRoute()
a = [x for x in ip.get_addr() if x['index'] == interface['index']]
print('\n8<--------------------- left operand')
pprint(a[0])
print('\n8<--------------------- right operand')
pprint(a[1])
print('\n8<--------------------- complement')
pprint(a[0] - a[1])
print('\n8<--------------------- intersection')
pprint(a[0] & a[1])
interface.remove().commit()
ip.close()
ipdb.release()
示例12: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class TestIPRoute(object):
ipnets = []
ipranges = []
ifnames = []
def setup(self):
self.ip = IPRoute()
self.ipnets = [allocate_network() for _ in range(3)]
self.ipranges = [[str(x) for x in net] for net in self.ipnets]
self.ifaces = []
self.ifnames = []
try:
self.dev, idx = self.create()
except IndexError:
pass
def create(self, kind='dummy'):
require_user('root')
name = uifname()
self.ip.link('add', ifname=name, kind=kind)
idx = None
while not idx:
idx = self.ip.link_lookup(ifname=name)
idx = idx[0]
self.ifaces.append(idx)
return (name, idx)
def uifname(self):
ifname = uifname()
self.ifnames.append(ifname)
return ifname
def teardown(self):
for net in self.ipnets:
free_network(net)
if hasattr(self, 'ifaces'):
for dev in reversed(self.ifaces):
try:
self.ip.link('delete', index=dev)
except:
pass
for name in reversed(self.ifnames):
try:
(self
.ip
.link('del', index=(self
.ip
.link_lookup(ifname=name)[0])))
except:
pass
self.ip.close()
def ifaddr(self, r=0):
return str(self.ipranges[r].pop())
def _test_nla_operators(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
r = [x for x in self.ip.get_addr() if x['index'] == self.ifaces[0]]
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') == self.dev
assert intersection['prefixlen'] == 24
assert intersection['index'] == self.ifaces[0]
def test_addr_add(self):
require_user('root')
ifaddr = self.ifaddr()
self.ip.addr('add', self.ifaces[0], address=ifaddr, mask=24)
assert '{0}/24'.format(ifaddr) in get_ip_addr()
def test_vlan_filter_dump(self):
require_user('root')
(an, ax) = self.create('bridge')
(bn, bx) = self.create('bridge')
self.ip.link('set', index=ax, state='up')
self.ip.link('set', index=bx, state='up')
assert len(self.ip.get_vlans()) >= 2
for name in (an, bn):
assert len(self.ip.get_vlans(ifname=name)) == 1
assert (self
.ip
.get_vlans(ifname=name)[0]
.get_attr('IFLA_IFNAME')) == name
assert (self
.ip
.get_vlans(ifname=name)[0]
.get_nested('IFLA_AF_SPEC',
'IFLA_BRIDGE_VLAN_INFO'))['vid'] == 1
def test_vlan_filter_add(self):
#.........这里部分代码省略.........
示例13: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class TestIPRoute(object):
def setup(self):
self.ip = IPRoute()
try:
self.dev, idx = self.create()
self.ifaces = [idx]
except IndexError:
pass
def create(self, kind='dummy'):
name = uifname()
create_link(name, kind=kind)
idx = self.ip.link_lookup(ifname=name)[0]
return (name, idx)
def teardown(self):
if hasattr(self, 'ifaces'):
for dev in self.ifaces:
try:
self.ip.link('delete', index=dev)
except:
pass
self.ip.close()
def _test_nla_operators(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
r = [x for x in self.ip.get_addr() if x['index'] == self.ifaces[0]]
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') == self.dev
assert intersection['prefixlen'] == 24
assert intersection['index'] == self.ifaces[0]
def test_addr_add(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
assert '172.16.0.1/24' in get_ip_addr()
def test_flush_addr(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.1.1', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.1.2', mask=24)
assert len(self.ip.get_addr(index=self.ifaces[0],
family=socket.AF_INET)) == 4
self.ip.flush_addr(index=self.ifaces[0])
assert len(self.ip.get_addr(index=self.ifaces[0],
family=socket.AF_INET)) == 0
def test_flush_rules(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', 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='172.16.200.1')
self.ip.rule('add', table=25, priority=250, dst='172.16.250.1')
assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 4
assert len(self.ip.get_rules(src='172.16.200.1')) == 1
assert len(self.ip.get_rules(dst='172.16.250.1')) == 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='172.16.200.1')) == 0
assert len(self.ip.get_rules(dst='172.16.250.1')) == 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_addr_filter(self):
require_user('root')
self.ip.addr('add',
index=self.ifaces[0],
address='172.16.0.1',
prefixlen=24,
broadcast='172.16.0.255')
self.ip.addr('add',
index=self.ifaces[0],
address='172.16.0.2',
#.........这里部分代码省略.........
示例14: main
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [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):
#.........这里部分代码省略.........
示例15: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import get_addr [as 别名]
class TestIPRoute(object):
def setup(self):
self.ip = IPRoute()
self.ap = AddrPool()
self.iftmp = 'pr2x{0}'
try:
self.dev, idx = self.create()
self.ifaces = [idx]
except IndexError:
pass
def get_ifname(self):
return self.iftmp.format(self.ap.alloc())
def create(self, kind='dummy'):
name = self.get_ifname()
create_link(name, kind=kind)
idx = self.ip.link_lookup(ifname=name)[0]
return (name, idx)
def teardown(self):
if hasattr(self, 'ifaces'):
for dev in self.ifaces:
try:
self.ip.link('delete', index=dev)
except:
pass
self.ip.close()
def _test_nla_operators(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
r = [x for x in self.ip.get_addr() if x['index'] == self.ifaces[0]]
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') == self.dev
assert intersection['prefixlen'] == 24
assert intersection['index'] == self.ifaces[0]
def test_add_addr(self):
require_user('root')
self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
assert '172.16.0.1/24' in get_ip_addr()
def _create(self, kind):
name = self.get_ifname()
self.ip.link_create(ifname=name, kind=kind)
devs = self.ip.link_lookup(ifname=name)
assert devs
self.ifaces.extend(devs)
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_neigh_real_links(self):
links = set([x['index'] for x in self.ip.get_links()])
neigh = set([x['ifindex'] for x in self.ip.get_neighbors()])
assert neigh < links
def test_mass_ipv6(self):
#
# Achtung! This test is time consuming.
# It is really time consuming, I'm not not
# kidding you. Beware.
#
require_user('root')
base = 'fdb3:84e5:4ff4:55e4::{0}'
limit = int(os.environ.get('PYROUTE2_SLIMIT', '0x800'), 16)
# add addresses
for idx in range(limit):
self.ip.addr('add', self.ifaces[0],
base.format(hex(idx)[2:]), 48)
# assert addresses in two steps, to ease debug
addrs = self.ip.get_addr(10)
assert len(addrs) >= limit
# clean up addresses
#
# it is not required, but if you don't do that,
# you'll get this on the interface removal:
#.........这里部分代码省略.........