0

I am able to run this properly using os.system. It is writing pcap file into text.

os.system("tshark -z 'proto,colinfo,tcp.srcport,tcp.srcport' -r filename.pcap > testfile")

But when I tried to give input file from termimal, I got following error: tshark: -z invalid argument

host = raw_input("Enter file name: ")   
test = subprocess.Popen(["tshark","-z","'proto,colinfo,tcp.srcport,tcp.srcport'","-r",host,">","testfile"], stdout=subprocess.PIPE)
output = test.communicate()[0]

Can anybody please figure out where I am making mistake?

1
  • Can you please post the full traceback you're receiving? Commented Feb 18, 2014 at 17:12

1 Answer 1

2

To emulate the os.system command, use the shell=True parameter to subprocess.Popen and provide the same command string (not an array of strings):

subprocess.Popen("tshark -z 'proto,colinfo,tcp.srcport,tcp.srcport' -r " 
                 + host + "> testfile", stdout=subprocess.PIPE, shell=True)

You need a shell to interpret your command line as you are using output redirection to a file ("> testfile").

In your example, you are passing each element of the string list to the execve() system call and hence as parameters to the tshark command (which gets 'proto,colinfo,tcp.srcport,tcp.srcport' as the argument to the -z option instead of proto,colinfo,tcp.srcport,tcp.srcport and which won't know what to do with the > and testfile arguments).

As wnnmaw points out in his comment, using os.system or subprocess.Popen with shell=True with command lines built from user input (the host variable in your case) allows a user to pass arbitrary data to the shell. This can be used to execute (potentially nasty) commands on your system.

For instance, setting host in your example to ; /bin/rm -rf / would delete every file on a UNIX system (assuming the user running the process had enough privilege).

It is therefore very important to validate an user input before adding it to the command string.

Sign up to request clarification or add additional context in comments.

2 Comments

You should probably make note of the security risk associated with shell=True and un-sanitized input
Thanks for valuabe comment---

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.