本文整理汇总了Python中pyroute2.IPRoute.addr方法的典型用法代码示例。如果您正苦于以下问题:Python IPRoute.addr方法的具体用法?Python IPRoute.addr怎么用?Python IPRoute.addr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyroute2.IPRoute
的用法示例。
在下文中一共展示了IPRoute.addr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_net
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import 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)
示例2: connect_to_br
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def connect_to_br(self):
index = 0
with docker_netns(self.name) as pid:
for quagga_config in self.quagga_config:
ip = IPRoute()
br = ip.link_lookup(ifname=quagga_config['bridge'])
if len(br) == 0:
ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
br = ip.link_lookup(ifname=quagga_config['bridge'])
br = br[0]
ip.link('set', index=br, state='up')
ifname = '{0}-{1}'.format(self.name, index)
ifs = ip.link_lookup(ifname=ifname)
if len(ifs) > 0:
ip.link_remove(ifs[0])
peer_ifname = '{0}-{1}'.format(pid, index)
ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
host = ip.link_lookup(ifname=ifname)[0]
ip.link('set', index=host, master=br)
ip.link('set', index=host, state='up')
guest = ip.link_lookup(ifname=peer_ifname)[0]
ip.link('set', index=guest, net_ns_fd=pid)
with Namespace(pid, 'net'):
ip = IPRoute()
ip.link('set', index=guest, ifname='eth{}'.format(index+1))
ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
ip.link('set', index=guest, state='up')
index += 1
示例3: del_addr
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def del_addr(self, ip):
iproute= IPRoute()
br = iproute.link_lookup(ifname=BRIDGE_INTERFACE_NAME)[0]
if not self.check_exists(ip, iproute, br):
iproute.addr('delete', br, address=ip, mask=30)
iproute.close()
iproute = None
示例4: LoopBackAddress
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import 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: initContainerNetwork
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def initContainerNetwork(self):
ip = IPRoute()
try:
addr = self['internal_ip'].split('/')[0]
mask = int(self['internal_ip'].split('/')[1])
except KeyError as e:
print("OpenvSwitch: CYGNET_INTERNAL_IP environment variable not found")
raise e
ip.addr('add',
index=(ip.link_lookup(ifname='br2')),
address=addr,
mask=mask)
run("ifconfig br2 up")
self.interfaces.append(('br2', (self.addr, str(mask))))
return addr
示例6: setUp
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def setUp(self):
b = BPF(arg1, arg2, debug=0)
fn = b.load_func("on_packet", BPF.SCHED_CLS)
ip = IPRoute()
ifindex = ip.link_lookup(ifname="eth0")[0]
# set up a network to change the flow:
# outside | inside
# 172.16.1.1 - 172.16.1.2 | 192.168.1.1 - 192.16.1.2
ip.addr("del", index=ifindex, address="172.16.1.2", mask=24)
ip.addr("add", index=ifindex, address="192.168.1.2", mask=24)
# add an ingress and egress qdisc
ip.tc("add", "ingress", ifindex, "ffff:")
ip.tc("add", "sfq", ifindex, "1:")
# add same program to both ingress/egress, so pkt is translated in both directions
ip.tc("add-filter", "bpf", ifindex, ":1", fd=fn.fd, name=fn.name, parent="ffff:", action="ok", classid=1)
ip.tc("add-filter", "bpf", ifindex, ":2", fd=fn.fd, name=fn.name, parent="1:", action="ok", classid=1)
self.xlate = b.get_table("xlate")
示例7: configure_link
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def configure_link(self, ip4_address, plen, gateway):
'''
Configure following attributes for interface inside the container
- Link-up
- IP Address
- Default gateway
'''
@staticmethod
def _intf_error(e, ifname, message):
raise Error(CNI_ERROR_CONFIG_NS_INTF, message + ifname +
' code ' + str(e.code) + ' message ' + e.message)
return
with CniNamespace(self.cni.container_netns):
iproute = IPRoute()
intf = iproute.link_lookup(ifname=self.cni.container_ifname)
if len(intf) == 0:
raise Error(CNI_ERROR_CONFIG_NS_INTF,
'Error finding interface ' +
self.cni.container_ifname + ' inside container')
idx_ns = intf[0]
try:
iproute.link('set', index=idx_ns, state='up')
except NetlinkError as e:
_intf_error(e, self.cni.container_ifname,
'Error setting link state for interface ' +
'inside container')
try:
iproute.addr('add', index=idx_ns, address=ip4_address,
prefixlen=plen)
except NetlinkError as e:
if e.code != errno.EEXIST:
_intf_error(e, self.cni.container_ifname,
'Error setting ip-address for interface ' +
'inside container')
try:
iproute.route('add', dst='0.0.0.0/0', gateway=gateway)
except NetlinkError as e:
if e.code != errno.EEXIST:
_intf_error(e, self.cni.container_ifname,
'Error adding default route inside container')
return
示例8: setUp
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def setUp(self):
b = BPF(arg1, arg2, debug=0)
fn = b.load_func("on_packet", BPF.SCHED_ACT)
ip = IPRoute()
ifindex = ip.link_lookup(ifname="eth0")[0]
# set up a network to change the flow:
# outside | inside
# 172.16.1.1 - 172.16.1.2 | 192.168.1.1 - 192.16.1.2
ip.addr("del", index=ifindex, address="172.16.1.2", mask=24)
ip.addr("add", index=ifindex, address="192.168.1.2", mask=24)
# add an ingress and egress qdisc
ip.tc("add", "ingress", ifindex, "ffff:")
ip.tc("add", "sfq", ifindex, "1:")
# add same program to both ingress/egress, so pkt is translated in both directions
action = {"kind": "bpf", "fd": fn.fd, "name": fn.name, "action": "ok"}
ip.tc("add-filter", "u32", ifindex, ":1", parent="ffff:", action=[action],
protocol=protocols.ETH_P_ALL, classid=1, target=0x10002, keys=['0x0/0x0+0'])
ip.tc("add-filter", "u32", ifindex, ":2", parent="1:", action=[action],
protocol=protocols.ETH_P_ALL, classid=1, target=0x10002, keys=['0x0/0x0+0'])
self.xlate = b.get_table("xlate")
示例9: set_parameter_higher_layer
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
def set_parameter_higher_layer(self, **kwargs):
"""
Set the parameter on higher layers of protocol stack (higher MAC and above)
Args:
param_key_value: key and value of this parameter
iface : interface name (required) e.g. "wlan0" (str)
ip_addres : interface ip adress e.g. "10.0.0.1" (str)
netmask : interface network mask e.g. 24 (int)
"""
if "iface" in kwargs:
iface = kwargs["iface"]
else:
return False
ipr = IPRoute()
idx = ip.link_lookup(ifname=iface)[0]
netmask=None
if "netmask" in kwargs:
netmask=kwargs["netmask"]
if "ip_address" in kwargs:
ip_address=kwargs["ip_address"]
ipr.addr('add', index=idx, address=ip_address, netmask=netmask)
return True
示例10: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import 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',
#.........这里部分代码省略.........
示例11: TestData
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
class TestData(object):
def setup(self):
create_link('dummyX', 'dummy')
self.release = Event()
self.ip = IPRoute()
self.dev = self.ip.link_lookup(ifname='dummyX')
def teardown(self):
self.ip.release()
self.release.set()
remove_link('dummyX')
remove_link('bala')
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))
#.........这里部分代码省略.........
示例12: main
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import 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):
#.........这里部分代码省略.........
示例13: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import 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)
#.........这里部分代码省略.........
示例14:
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import addr [as 别名]
netns.create('test')
# create VETH pair and move v0p1 to netns 'test'
ip.link_create(ifname='v0p0', peer='v0p1', kind='veth')
idx = ip.link_lookup(ifname='v0p1')[0]
ip.link('set',
index=idx,
net_ns_fd='test')
# bring v0p0 up and add an address
idx = ip.link_lookup(ifname='v0p0')[0]
ip.link('set',
index=idx,
state='up')
ip.addr('add',
index=idx,
address='10.0.0.1',
broadcast='10.0.0.255',
prefixlen=24)
# create a route with metrics
ip.route('add',
dst='172.16.0.0/24',
gateway='10.0.0.10',
metrics={'mtu': 1400,
'hoplimit': 16})
# release Netlink socket
ip.close()
示例15: TestIPRoute
# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import 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):
#.........这里部分代码省略.........