Search code examples
pythonpython-3.xsubprocesspopennetcat

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


In Python3 using subprocess.Popen, I would like to capture the output and command return code for this "nc -z 192.168.25.14 22" command. Here is my sample code: #!/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()

and an example of the output is

*Commands is ['nc', '-vZ', '192.168.25.14', '22']

os.wait:exit status != 0

STDERR is <_io.BufferedReader name=12>

STDOUT is <_io.BufferedReader name=9>

STDIN is <_io.BufferedWriter name=8>*

I'm assuming that I have an error in my code or logic, but I can not figure it out. I have used similar code for other commands like ssh and ls without issues. For this "nc" command I get the same set of output/messages regardless of whether or not there is an open port 22 at the host address.

Thanks...RDK


Solution

  • OK, as I did not get any useful replies to this question, I changed the code from subprocess.Popen to subprocess.run as shown below. This modification worked for my requirements as ncdup.stderr contained the information I was looking for.

          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)