python - 尝试从 check_output 接收输出时出错

python - Error when trying to receive output from check_output

我的代码应该追踪一个用 scapy 嗅探的数据包并检查哪个程序 sent/received 该数据包,如果找不到该程序 "Unknown"

代码:

source_software = check_output(["netstat", "-nb"], shell = True).decode()
source_software = source_software[source_software.find(str(packet_dictionary["Port"])) : ]
source_software = source_software[source_software.find("\n") + 2 : source_software.find("]")]
if "Can not" not in source_software and len(source_software) > MINIMUM_LENGTH:
    packet_dictionary["Software"] = source_software
else:
    packet_dictionary["Software"] = "Unknown"

错误:

File "Client.py", line 44, in add_to_list
source_software = check_output(["netstat", "-nb"], shell = True).decode()
File "C:\Python36\lib\subprocess.py", line 336, in check_output
**kwargs).stdout
File "C:\Python36\lib\subprocess.py", line 418, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['netstat', '-nb']' returned non-zero 
exit status 1.

正如您在异常的底线看到的那样,问题在于:

Command '['netstat', '-nb']' returned non-zero exit status 1.

...这意味着它与 check_output 本身无关,而只是报告您尝试 运行 使用它的命令失败并以代码 1 退出。

您可能想要 运行 shell 中的命令并检查它是否按预期工作。

可能是python没有运行 netstat 或其他任何权限,但您可以使用以下命令进行调试

source_software = check_output("netstat -nb;  exit 0", stderr=subprocess.STDOUT, shell=True).decode()
print source_software