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
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With