3

I want execute netcat command from my python script, so I use the 'subprocess.Popen', but the problem is that the output of this command is directly printed in may shell console, i want o get him in a variable , so i can do some modification before printing it.

res = subprocess.Popen("nc -v 192.168.1.1 25", stdout=subprocess.PIPE, stderr=None, shell=True)
#output = res.communicate()
#output = str(output)
#print output
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
user3383192
  • 43
  • 1
  • 5
  • Have you tried also to redirect `stderr`? It is unlikely that `nc` would print directly to the terminal unless to prompt you for the password – jfs Mar 13 '14 at 17:21
  • Here's a [code example that shows how to capture output even if it is redirected to the terminal (outside of stdout/stderr streams)](http://stackoverflow.com/a/22253472/4279). – jfs Mar 13 '14 at 17:28
  • i confirme that, when i use the ls -l in place of nc , it work, so the nc command put the result even if you dont use print command, what could be the solution?? – user3383192 Mar 13 '14 at 17:29
  • 1
    For something simple like this why not just use a socket directly? – Keith Mar 13 '14 at 17:38

2 Answers2

1

If you want make calling shell commands easy to yourself in Python use sh library.

In sh this would be:

  from sh import nc
  output = nc("-v", "192.168.1.1", "25")  # output is string of the command output

As always, installing Python libraries are recommended to do with virtualenv.

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
0

I use this to capture output from a system command, note that it will only get the last line. Modify around lastline as needed to get more:

def GetOutput(command):
    lastline = os.popen(command).readlines()
    result = lastline[0].rstrip()
    return result
McNandy
  • 23
  • 5