Subprocess Variables

John Riselvato picture John Riselvato · Dec 3, 2010 · Viewed 33.3k times · Source
  1 import subprocess
  2 raw = raw_input("Filename:").lower()
  3 ip = raw_input("Host:").lower()
  4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True)

So this is my script. I everything works besides one key objective, using the raw input. It allows me to input anything i want, but when it goes to saving the file or using an ip/host doe doesn't actually do anything. Sure it gives me the packets, but from the localhost not the host i type in.

how i know this isn't working is cause my first raw input is the filename, so i put in test, when i look in the folder were my script is, it produces a file called "raw" meaning, its not actually taking my input only using whats inside my "X"...

So i make a few chances to come to this:

  1 import subprocess
  2 raw = raw_input("Filename:").lower()
  3 ip = raw_input("Host:").lower()
  4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw + "host" + ip,shell=True)

Which is great because it actually calls for the -w but it saves it now as rawhostip instead of "raw"s input. for reference this is what the command looks like in the terminal:

tcpdump -c5 -vvv -w savename host wiki2

the only two variabls are savename and wiki2 the rest are needed for the command to work.

with this script i get this error:

import subprocess
raw = raw_input("Filename:").lower()
ip = raw_input("Host:").lower()
cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw, "host" + ip,shell=True)

Error:

Traceback (most recent call last):
  File "te.py", line 4, in <module>
    cmd = subprocess.call("tcpdump -c5 -vvv -w" + raw, "host" + ip,shell=True)
  File "/usr/lib/python2.6/subprocess.py", line 480, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.6/subprocess.py", line 583, in __init__
    raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

I am at a lost. Any help will be great, yes I know look at subprocess's doc's on site:X, I have I need a human to teach me, I don't understand what I am reading.

My question is how do I work with these variables.

Answer

user225312 picture user225312 · Dec 3, 2010

Don't use shell=True. That should be False.

You are making subtle mistakes with the input. Specifically, if you have two strings:

>>> s1 = 'Hello'
>>> s2 = 'Hi'
>>> s1 + s2
'HelloHi'

Notice, there is no space between Hello and Hi. So don't do this. (Your line 4)

You should do (the good way):

>>> raw = raw_input('Filename: ')
Filename: test
>>> ip = raw_input('Host: ')
Host: 192.168.1.1 
>>> command = 'tcpdump -c5 -vvv -w {0} {1}'.format(raw, ip)   # the command goes here
>>> subprocess.call(command.split(), shell=False)   # call subprocess and pass the command as a list using split

Now it should work.