gpt4 book ai didi

python - 通过 python 创建一个 vlan 并将其添加到网络命名空间

转载 作者:行者123 更新时间:2023-12-04 16:56:02 26 4
gpt4 key购买 nike

是否可以在python中编写以下命令?

在终端中:

#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 bananapi@192.168.1.11

在python3.4中,我成功地创建了一个带有pyroute2的vlan
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

但是有没有办法将这个 vlan 添加到一个命名空间并在这个命名空间中执行一个进程?

我的方法(不起作用):
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()))

最佳答案

我自己找到了解决方案。

ipdb = IPDB()
ipdb_netns = IPDB(nl=NetNS('vnsp0'))

program_command = ['ssh','bananapi@192.168.1.12']
#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()

关于python - 通过 python 创建一个 vlan 并将其添加到网络命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33849847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com