如何将 Python 的 cmd 类的输入/输出通过管道传输到另一个 Python 进程?



目前,我正在用Mininet Wifi进行一个实验。它的CLI是Python的Cmd模块,这就是我能够获得有关模拟网络环境的准确信息的方式。模拟器在Ubuntu 14.04或更高版本上以sudo-python的身份作为自己的进程运行。

此网络的远程控制器是POX。这一次,只有一个脚本在运行;一切都通过预设的命令实现自动化,不再需要人工交互。我想做的是:POX进程需要将命令注入Mininet的进程,并检索该命令的执行结果。这是因为POX的逻辑必须通过Mininet不断查询网络状态才能做出决策。当做出决定后,POX必须再次向Mininet进程注入命令以更改网络状态。

附录:目前,由于名为m的实用程序函数,我只能在运行sudo python a_Mininet_script时访问Mininet派生的主机。生成主机后,Mininet进入其CLI功能,这是我想与之通信但无法与之通信的功能。这是Mininet的m功能。

#!/bin/bash
# Attach to a Mininet host and run a command
if [ -z $1 ]; then
echo "usage: $0 host cmd [args...]"
exit 1
else
host=$1
fi
pid=`ps ax | grep "mininet:$host$" | grep bash | grep -v mnexec | awk '{print $1};'`
if echo $pid | grep -q ' '; then
echo "Error: found multiple mininet:$host processes"
exit 2
fi
if [ "$pid" == "" ]; then
echo "Could not find Mininet host $host"
exit 3
fi
if [ -z $2 ]; then
cmd='bash'
else
shift
cmd=$*
fi
cgroup=/sys/fs/cgroup/cpu/$host
if [ -d "$cgroup" ]; then
cg="-g $host"
fi
# Check whether host should be running in a chroot dir
rootdir="/var/run/mn/$host/root"
if [ -d $rootdir -a -x $rootdir/bin/bash ]; then
cmd="'cd `pwd`; exec $cmd'"
cmd="chroot $rootdir /bin/bash -c $cmd"
fi
cmd="exec sudo mnexec $cg -a $pid $cmd"
eval $cmd

例如,要从任何终端访问h1的终端,而不是从POX脚本,我会这样称呼它:

sh m h1 ifconfig

但要从子流程调用它,它将是:

p = subprocess.Popen('echo my passwd | sudo -kS sh m h1 ifconfig', shell = True)

为了重复我的问题,我想从POX控制器与Mininet进程的CLI通信,而不仅仅是与派生的主机通信。

我想你想实现类似netstat-oan|findstr 80的函数(这是在windows上查找端口80),这是将netstat-oan的输出传递给命令findstr的管道命令。

然后python代码类似于:

import subprocess
p1 = subprocess.Popen('netstat -oan', stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen('findstr 80', stdin=p1.stdout, stdout=subprocess.PIPE, shell=True)
pipeline_output = p2.communicate()[0]
print pipeline_output

然后,p1进程的输出将传递给p2进程,仅供参考。

最新更新