Search code examples
phpsshcommand-line-interface

How to run CLI commands in PHP on another server using SSH?


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.


Solution

  • 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