问题
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.
回答1:
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
回答2:
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
回答3:
Require:
sudo apt install php-ssh2
This example will receive the output of ls -ltrapR
from the remote php server.
#!/usr/bin/php
<?php
$con=ssh2_connect('223.245.xx.xx', 22);
ssh2_auth_password($con, 'root', 'bybyDRRxxxx');
$shell=ssh2_shell($con, 'xterm');
$stream = ssh2_exec($con, 'ls -ltrapR');
stream_set_blocking($stream, true);
$out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($out);
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.
来源:https://stackoverflow.com/questions/50525256/how-to-run-cli-commands-in-php-on-another-server-using-ssh