到目前为止,我有一个代码可以过滤除了 网关 </跨度> IP(路由-n | awk’{if($ 4 ==“UG”)打印$ 2}’),但我正在试图弄清楚如何将它传递给Python中的变量。这是我得到的:
进口shlex;来自子进程导入Popen,PIPE;
cmd =“route -n | grep’UG [\ t]‘| awk’{print $ 2}’”;
网关 </跨度> = Popen(shlex.split(cmd),stdout = PIPE);gateway.communicate();exit_code = gateway.wait();
有任何想法吗?
注意:我是新手。
无论好坏,你的 cmd 使用shell管道。要在子进程中使用shell功能,必须设置 shell=True :
cmd
shell=True
from subprocess import Popen, PIPE cmd = "/sbin/route -n | grep 'UG[ \t]' | awk '{print $2}'" gateway = Popen(cmd, shell=True, stdout=PIPE) stdout, stderr = gateway.communicate() exit_code = gateway.wait()
或者,人们可以保持 shell=False ,消除管道,并在python中执行所有字符串处理:
shell=False
from subprocess import Popen, PIPE cmd = "/sbin/route -n" gateway = Popen(cmd.split(), stdout=PIPE) stdout, stderr = gateway.communicate() exit_code = gateway.wait() gw = [line.split()[1] for line in stdout.decode().split('\n') if 'UG' in line][0]
由于外壳加工的变幻莫测,除非有特殊需要,否则最好避免 shell=True 。