尝试使用 Python3 中的 subprocess.Popen 获取 "nc -vz <host> <port>" 命令的输出和 return 代码

trying to get the output and return code for "nc -vz <host> <port>" command using subprocess.Popen in Python3

在 Python3 中使用 subprocess.Popen,我想捕获此 "nc -z 192.168.25.14 22" 命令的输出和命令 return 代码。这是我的示例代码: #!/usr/bin/env python import urllib.request, urllib.error, urllib.parse import subprocess import time # set up null file for pipe messages nul_f = open('/dev/null', 'w') # try loop for clean breakout with cntl-C try: with open('/mnt/usbdrive/output/Urls.txt') as f: for line in f: data = line.split() commands = ['nc', '-vZ', data[1], data[0]] print(commands) try: ncdmp = subprocess.Popen(commands , stderr=subprocess.PIPE, stdout=subprocess.PIPE,) except OSError: print ("error: popen") exit(-1) # if the subprocess call failed, there's not much point in continuing ncdmp.wait() if ncdmp.returncode != 0: print(" os.wait:exit status != 0\n") else: print ("os.wait:", ncdmp.pid, ncdmp.returncode) print("STDERR is ", ncdmp.stderr) print("STDOUT is ", ncdmp.stdout) print("STDIN is ", ncdmp.stdin) except KeyboardInterrupt: print('Done', i) # clean up pipe stuff ncdmp.terminate() ncdmp.kill() nul_f.close()

输出示例为

*命令是 ['nc', '-vZ', '192.168.25.14', '22']

os.wait:退出状态!= 0

STDERR 是 <_io.BufferedReader name=12>

STDOUT 是 <_io.BufferedReader name=9>

STDIN 是 <_io.BufferedWriter name=8>*

我假设我的代码或逻辑有错误,但我无法弄清楚。我对其他命令(如 ssh 和 ls)使用了类似的代码,没有出现问题。对于这个 "nc" 命令,无论主机地址是否有开放的端口 22,我都会得到相同的 output/messages 集。

谢谢...RDK

好的,因为我没有得到任何有用的回复这个问题,我将代码从 subprocess.Popen 更改为 subprocess.run 如下所示。此修改符合我的要求,因为 ncdup.stderr 包含我正在寻找的信息。

      commands = shlex.split("nc -vz " + "-w 5 " + data[1] + " " + data[0])
      try:
        ncdmp = subprocess.run(commands , capture_output=True)
      except OSError:
          print ("error: popen")
        exit(-1) 
      err_line = str(ncdmp.stderr)