-3

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
Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
Barak
  • 43
  • 7
  • 1
    The redirection is a shell feature. Use `shell=True` and give the command line as a string. Also read https://docs.python.org/3/library/subprocess.html#security-considerations – Klaus D. Mar 30 '22 at 09:31
  • I fell like you should remove ' ' from around the `>` operator – matszwecja Mar 30 '22 at 09:31
  • 2
    Yes: [How to redirect output with subprocess in Python?](https://stackoverflow.com/questions/4965159/how-to-redirect-output-with-subprocess-in-python) – mkrieger1 Mar 30 '22 at 09:33

1 Answers1

0

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.

VPfB
  • 14,927
  • 6
  • 41
  • 75