Pyroute2模块

Posted by YangSijie Blog on June 24, 2018

pyroute2模块

简介:该模块可以用来管理网络命名空间,也可以用来创建虚拟网卡

该模块分为两种方式:

  • pyroute2.IPRoute()方式

  • pyroute2.IPDB()方式

当程序需要频繁的操作的时候,建议使用第二种。

此处介绍一种创建命名空间,并且自动开启其中的网卡的demo代码:

from pyroute2 import IPDB
from pyroute2 import NetNS

# generate a netns
# Mind its path!!! Which is not in `/var/run/netns/`, so it can not be shown
# by using 'ip netns'. But you can create a symbol link.
ns0 = NetNS('/var/run/netns/ns0')

# start the main network settings database
ip_main = IPDB()
# start the same for a netns
ip_ns0 = IPDB(nl=ns0)

# create VETH
ip_main.create(ifname='veth0', kind='veth', peer='veth1').commit()

# move peer VETH into netns (this move will clear all settings in this device)
with ip_main.interfaces['veth1'] as veth:
    veth.net_ns_fd = '/var/run/netns/ns0'

# now, set 'veth0' up
with ip_main.interfaces['veth0'] as veth:
    veth.add_ip('172.16.14.1/24')
    veth.set_address('00:11:22:33:44:55')
    veth.set_mtu(9000)
    veth.up()
    
# now, netns has a device and it should be up
with ip_ns0.interfaces.veth1 as veth:
    veth.add_ip('172.16.147.2/24')
    veth.set_mtu(9000)
    veth.up()

# don't forget release the database
ip_main.release()
ip_ns0.release()

还有一种方式,与上述差不多,但是可以用于修改网卡名:

from pyroute2 import IPDB
from pyroute2 import NetNS

ns0 = NetNS('/var/run/netns/ns0')

ip_main = IPDB()
ip_ns0 = IPDB(nl=ns0)

ip_main.create(ifname='veth0', kind='veth', peer='veth1').commit()

with ip_main.interfaces['veth1'] as veth:
    veth.net_ns_fd = '/var/run/netns/ns0'

# 使用这种方法一定要注意最后加上commit()使得配置生效
ip_main.interfaces['veth0'].add_ip('172.16.147.1/24')
ip_main.interfaces['veth0'].set_mtu(9000)
ip_main.interfaces['veth0'].up()
ip_main.interfaces['veth0'].commit()


ip_ns0.interfaces.veth1.add_ip('172.16.147.2/24')
ip_ns0.interfaces.veth1.set_mtu(9000)
ip_ns0.interfaces.veth1.set_address('00:11:22:33:44:55')
ip_ns0.interfaces.veth1.ifname = 'eth0'		# 将原网卡名`veth1`更改为`eth0`
ip_ns0.interfaces.veth1.up()
ip_ns0.interfaces.veth1.commit()

ip_main.release()
ip_ns0.release()

删除一个命名空间可以用这种方式:

from pyroute2 import NetNS

ns0 = NetNS('test0')
# ...
ns0.close()
ns0.remove()

删除一个网卡:

from pyroute2 import IPDB

ipdb = IPDB()
with ipdb.interfaces['ve0'] as veth:
    veth.remove()