I am trying to run CLI commands in PHP but on a different server. In order to run the command on the other server I am using the linux ssh
command. In order to run the CLI command in PHP I am using exec()
.
This works...
$output = exec('cut -d: -f1 /etc/passwd'); //works!
This works from the command line of one server to another...
ssh my.otherserver.com "date"
But, when I try to do this in PHP it does not work...
$output = exec('ssh my.otherserver.com "date"'); //does not work!
Is what I am trying to do possible? How do I do this? Thanks in advance.
to connet to your server with ssh you need to use
ssh2_exec
php function.I recommed you to use phpseclib, it's a wrapper for PHP SSH implementation
Require:
This example will receive the output of
ls -ltrapR
from the remote php server.Pay attention as it is just using basic auth (Fine trought ssl, better use a vpn). It can be securised furthermore with cryptographic keys and else.
ssh2_connect or phpseclib
You can use ssh2_connect or phpseclib. On my EC2 instance I had to install the package for ssh2_connect (e.g. yum install php56-pecl-ssh2-0.12-5.15.amzn1.x86_64) as it wasn't there by default. Note: this could be done with a bash script as well.
Further reading:
http://phpseclib.sourceforge.net/
http://php.net/manual/en/function.ssh2-connect.php