Issue
I am trying to print out my outputs into a log file, I am using python with subprocess to do so. But when I use > in code, I am getting error like:
+ klm.py scan /home '>' /home/userA/out/home_03-30-2022_11-07-32.log
2022-03-30 09:09:21,074 ERROR > does not exist
Here is the code I am running:
subprocess.run(['sudo', 'docker', 'run', '-it', '--rm', '-w', '/workdir', '-v', f'{pwd}:/workdir:ro', 'docker-local.abc.xyz.xyz.name.com/klm', 'klm.py', 'scan', f"{pwd}", ">", f'/home/userA/out{directory}_{date_time}.log'])
Whenever I use the command itself directly into the terminal, command is working working without any error and creating the .log files, I assume this is error coming from subprocess or python side.
> directory variable is a for loop of list elements -> DIRECTORIES = [/home, /root, etc]
> datetime just a string -> date_time
> pwd is -> pwd = os.getcwd()
> I don't know if it is useful info but I am using Kali Linux for this
Solution
I'd like to show a standard output redirection on a simpler command. It prints the date and time to a file. First using shell's redirection and then without the shell's help (shell=False
is the default)
import subprocess
# with shell redirection
subprocess.run(['date >out1.txt'], shell=True)
# without shell
with open('out2.txt', 'w') as out:
subprocess.run(['date'], stdout=out)
Note: the documentation asks you to read the Security Considerations before using shell=True
.
Answered By - VPfB Answer Checked By - Candace Johnson (WPSolving Volunteer)