Reputation: 776
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.
Upvotes: 2
Views: 6163
Reputation: 13129
Require:
sudo apt install php-ssh2
This example will receive the output of ls -a
from the remote server.
#!/usr/bin/php
<?php
$com = ssh2_connect('223.245.xx.xx', 22);
ssh2_auth_password($com, 'root', 'password');
$shell = ssh2_shell($com, 'xterm');
$stream = ssh2_exec($com, 'ls -a');
stream_set_blocking($stream, true);
$out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($out);
It can be secured furthermore with cryptographic keys and else.
Upvotes: 2
Reputation: 7327
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.
<?php
//ssh2_connect:
$connection = ssh2_connect('localhost', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'ls -l > /tmp/worked.txt');
//phpseclib:
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.example.com');
$ssh->login('username', 'password') or die("Login failed");
echo $ssh->exec('command');
Further reading:
http://phpseclib.sourceforge.net/
http://php.net/manual/en/function.ssh2-connect.php
Upvotes: 1