Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executed piped commands via System.Diagnostics.Process on Mono

Tags:

c#

mono

Is it possible to execute the following piped commands via System.Diagnostics.Process?

echo "test" | sudo -S shutdown -r +1

I've tried setting the file name to "/bin/bash", with the above as arguments, with no success.

...
var processStartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = "echo \"test\" | sudo -S shutdown -r +1" };
process.StartInfo = processStartInfo;
...
like image 463
csano Avatar asked Aug 15 '13 21:08

csano


1 Answers

bash is interpreting your command as a file name followed by arguments, meaning it invokes echo and passes all the rest (including the pipe |) to it for printing so you will get test | sudo -S shutdown -r +1 echoed and sudo won't be executed.

You should use the -c option to execute a command. Furthermore, you should quote the command itself so that it gets passed as a single argument. Something like this should work:

var processStartInfo = new ProcessStartInfo
{
    FileName = "/bin/bash",
    Arguments = "-c \"echo test | sudo -S shutdown -r +1\""
};
like image 79
Jester Avatar answered Sep 28 '22 07:09

Jester