I am passing dynamic shell commands over SSH to servers with PHP
using the ssh2
library. The command I am passing is (note this is just an example, the commands are dynamic and user generated).
$command = 'ls -al
free -m';
Notice the newline, this is required, since users can type full bash scripts with newlines and tabs. Then, I do the following to build the actual command to execute with the ssh2 library:
$command = str_replace("'", "\'", $command);
$command = 'echo $\'' . $command . '\' | bash';
Which results in the final command of:
echo $'ls -al
free -m' | bash
The above command executes fine at the shell directly, but when I execute it from PHP using ssh2, and I getting:
ls: invalid option --
Try `ls --help' for more information.
So I thought, ok there must be some special characters or the dollar sign is not being escaped, so I did:
print_r(bin2hex($command));
Which results in:
6563686f2024276c73202d616c0d0a66726565202d6d27207c2062617368
Converting the hex into ascii returns the correct command (exactly as above) though.
Any idea what could be causing this?