Skip to content
Advertisement

Unable to redirect output from bash

I’m trying to run a command through PHP for a project and have the output redirected to a file.

On PHP, I’m creating a string and running the shell_exec() function with the string as a parameter:

$command = "my_commands";
$output = shell_exec($command);
echo $output;

To be able to run things as root through PHP and shell_exec, I use the following:

bash -lc 'echo **my_linux_password** | /usr/bin/sudo -S **my_commands** &'

An example of this is as follows:

bash -lc 'echo **my_linux_password** | /usr/bin/sudo ... &' 2>&1 | tee /home/kali/Desktop/logs/file.txt

(See end of code above) Am I putting the `2>&1 | tee /home/kali/Desktop/logs/file.txt` in the right place? I don’t seem to be getting any files created. The command works just fine without this output redirect part…

Advertisement

Answer

You’re running the sudo command in the background, so the “outer” bash process does not receive the output for redirection.

You’ll have to do something like

bash -lc 'echo **my_linux_password** | /usr/bin/sudo sh -c "my_command | tee /home/kali/Desktop/logs/file.txt 2>&1" &'

And you’re now firmly in quoting hell.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement