subprocess.Popen中|管道符号失效,无法过滤Wi-Fi IP地址
解决subprocess.Popen处理管道符号失效的问题
你的猜测没错,subprocess.Popen默认不处理管道符号|——管道是系统shell的功能,默认模式下Popen会直接执行指定程序,把|、findstr这些当成目标程序(这里是netsh)的参数,所以netsh会识别为无效参数,返回用法提示。
有两种可行的解决思路:
方法一:开启shell模式
将整个命令作为字符串传入,同时设置shell=True,让系统shell来解析管道逻辑:
from subprocess import Popen, PIPE # 执行带管道的命令,shell=True交给系统shell处理 output, error = Popen( 'netsh interface ip show addresses Wi-Fi | findstr /ir "IP Address"', shell=True, stdout=PIPE, stderr=PIPE, text=True ).communicate() # 打印过滤后的IP地址信息 print(output.strip())
注意:text=True让输出直接是字符串格式,无需手动解码;shell=True虽然方便,但如果命令包含用户输入,存在shell注入风险,需谨慎使用。
方法二:手动串联进程(无shell,更安全)
不依赖shell,直接创建两个Popen实例,把第一个进程的输出作为第二个进程的输入:
from subprocess import Popen, PIPE # 第一步:执行netsh命令,获取原始输出 netsh_process = Popen( ['netsh', 'interface', 'ip', 'show', 'addresses', 'Wi-Fi'], stdout=PIPE, text=True ) # 第二步:将netsh的输出作为findstr的输入,过滤IP信息 findstr_process = Popen( ['findstr', '/ir', 'IP Address'], stdin=netsh_process.stdout, stdout=PIPE, stderr=PIPE, text=True ) # 关闭netsh的stdout,确保findstr能收到EOF netsh_process.stdout.close() # 获取最终结果 output, error = findstr_process.communicate() print(output.strip())
这种方式完全绕过shell,避免了注入风险,适合对安全性要求较高的场景。
内容的提问来源于stack exchange,提问作者phpjunkie
相关产品推荐
相关产品推荐

