试图获取输出并返回代码“ nc -vz ”使用subprocess.Popen in Python3 ] >>

问题描述 投票:0回答:1

在使用subprocess.Popen的Python3中,我想捕获此“ nc -z 192.168.25.14 22”命令的输出和命令返回代码。这是我的示例代码: #!/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']

等待等待:退出状态!= 0

STDERR是<_io.bufferedreader>

STDOUT是<_io.bufferedreader>

STDIN是<_io.bufferedwriter> *

我假设我的代码或逻辑中有错误,但我无法弄清楚。我对其他命令(例如ssh和ls)使用了类似的代码,没有出现问题。对于此“ nc”命令,无论主机地址处是否有开放端口22,我都会获得相同的输出/消息集。]

谢谢... RDK

在使用subprocess.Popen的Python3中,我想捕获此“ nc -z 192.168.25.14 22”命令的输出和命令返回代码。这是我的示例代码:#!/ usr / bin / env python import ...

python python-3.x subprocess popen netcat
1个回答
0
投票

[确定,因为我没有得到对此问题的任何有用答复,所以我将代码从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)
© www.soinside.com 2019 - 2024. All rights reserved.