Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.Popen shell=True to shell=False

I know that it is bad practice to use shell=True for subprocesses. However for this line of code, I'm not sure how to execute it with shell=False

subprocess.Popen('candump -tA can0 can1 >> %s' %(file_name), shell=True)

Where the command I want to run is:

candump -tA can0 can1 >> file_name

Where file_name is /path/to/file.log

like image 658
avelampudi Avatar asked Jan 04 '17 18:01

avelampudi


People also ask

Should I use shell true in subprocess?

We should avoid using 'shell=true' in subprocess call to avoid shell injection vulnerabilities. In this call you have to pass a string as a command to the shell. If call_method is user controlled then it can be used to execute any arbitrary command which can affect system.

How can we avoid shell true in subprocess?

From the docs: args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

Why are shells true in subprocess?

Setting the shell argument to a true value causes subprocess to spawn an intermediate shell process, and tell it to run the command. In other words, using an intermediate shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run.

What does Popen shell do?

The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read- only or write-only.


1 Answers

You can't directly use piping in the command the way you do with shell=True, but it's easy to adapt:

with open(file_name, 'ab') as outf:
    proc = subprocess.Popen(['candump', '-tA', 'can0', 'can1'], stdout=outf)

That opens the file at the Python level for binary append, and passes it as the stdout for the subprocess.

like image 98
ShadowRanger Avatar answered Oct 01 '22 04:10

ShadowRanger