Is it possible to program the following commands in python?
In a terminal:
#create a vlan
ip link add name Lan1 link eth0 type vlan id 10
ip addr add 192.168.1.11/24 brd 192.168.1.255 dev Lan1
#create a namespace
ip netns add vnsp1
#connect the vlan with the namespace
ip link set Lan1 netns vnsp1
ip netns exec vnsp1 ifconfig Lan1 192.168.1.11/24 up
#execute a program inside the namespace
ip netns exec vnsp1 ssh [email protected]
In python3.4 I successfully created a vlan with pyroute2
from pyroute2 import IPDB
from subprocess import PIPE
from pyroute2 import NetNS, NSPopen, netns
ipdb = IPDB()
link_iface = self.ipdb.interfaces['eth0']
with self.ipdb.create(kind="vlan", ifname='Lan1', link=link_iface, vlan_id=10) as i:
i.add_ip('192.168.1.11', 24)
i.mtu = 1400
but is there a way to add this vlan to a namespace and execute a process in this namespace?
My approach (is not working):
vnsp = netns.create('vnsp0')
self.ipdb.interfaces['Lan1'].net_ns_fd = vnsp_name
nsp = NSPopen('vnsp0', 'ping','-c 1','192.168.1.12', stdout=PIPE)
print("output: " + str(nsp.communicate()))
I found a solution by myself.
ipdb = IPDB()
ipdb_netns = IPDB(nl=NetNS('vnsp0'))
program_command = ['ssh','[email protected]']
#create vlan
link_iface = ipdb.interfaces['eth0']
with ipdb.create(kind="vlan", ifname='Lan1', link=link_iface, vlan_id=10).commit() as i:
i.add_ip('192.168.1.11', 24)
i.mtu = 1400
i.up()
#add namespace
with ipdb.interfaces.Lan1 as lan:
lan.net_ns_fd = 'vnsp0'
with ipdb_netns.interfaces.Lan1 as lan:
lan.add_ip('192.168.1.11/24')
lan.up()
#execute program
nsp = NSPopen('vnsp0', program_command, stdout=PIPE)
print("output: " + str(nsp.communicate()))
nsp.wait()
nsp.release()