将变量设置为网关IP

时间:2015-05-13 04:42:30

标签: python awk gateway

到目前为止,我有一个代码可以过滤除网关IP(route -n | awk '{if($4=="UG")print $2}')之外的所有内容,但我正在尝试弄清楚如何将其传递给Python中的变量。这就是我得到的:

import shlex;
from subprocess import Popen, PIPE;

cmd = "route -n | grep 'UG[ \t]' | awk '{print $2}'";
gateway = Popen(shlex.split(cmd), stdout=PIPE);
gateway.communicate();
exit_code = gateway.wait();

有什么想法吗?

注意:我是新手。

1 个答案:

答案 0 :(得分:1)

无论好坏,您的cmd都使用了shell管道。要在子流程中使用shell功能,必须设置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中执行所有字符串处理:

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处理的变幻莫测,除非有特殊需要,否则最好避免使用shell=True