python - 将变量设置为网关 IP

标签 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();

有什么想法吗?

注意:我是新手。

最佳答案

无论好坏,您的 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

关于python - 将变量设置为网关 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30205842/

相关文章:

python - 没有版本检查或 `six`,如何使用 `except MyError, e:`和 `except MyError as e`来与Python 2&3一起使用?

Javascript/Jquery 将变量一分为二以实现 Stripe 集成

Linux top -b 只显示特定列

linux - 使用 awk 从文件中读取元组

bash - 我可以链接多个命令并使它们都从标准输入获取相同的输入吗?

android - 是否可以将两个不同的默认网关添加到 android 中两个不同 NIC 的路由表中?

email - 我发送到 vtext.com 的电子邮件停止工作

python - 具有绝对 URL 路径的 Django 压缩器和 clevercss

如果值不存在,Python 字典返回请求的键

python - 从 Flask 应用程序运行 scrapy