phpsshphpseclibssh2

PHPSECLIB and SSH2


I have been looking for a solution on how I could use php to establish a connection to a remote server and execute commands. Researching has brought two solutions to my attention; phpseclib and ssh2. I will try and keep my questions from turning this into a comparison post. From what I can tell they are both widely used solutions. ssh2 is a php extension while phpseclib is a pure php library. It seems that you can also use phpseclib in conjunction with ssh2. I would much prefer to avoid needing to install an extension so I am more inclined to use phpseclib. However I do have some concerns.

ssh2 has direct documentation with php does this mean it is a better solution to use?

Most of the posts I see regarding phpseclib are several years old, is this still a "modern-ish" solution?

phpseclib (found here) says it was built for compatability with php 4 with 2.0 being geared towards php 5. Is this an acceptable solution to those working with php 7?

Here is an example using an RSA key to establish a ssh connection with phpseclib 2.0

require __DIR__ . '/vendor/autoload.php';

use phpseclib\Net\SSH2;
use phpseclib\Crypt\RSA;

$ssh = new SSH2('www.domain.tld');
$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));
if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');

I am still fairly new to ssh but if I understand the above correctly, so long as the remote server has a .pub key I can simply supply my connection with my local private key (and user) and I should be able to connect? Does the public key need to be somewhere specific?


Solution

  • phpseclib 1.0, in theory, works on PHP 4.4, but phpseclib 2.0 requires PHP 5.3+. 3.0 requires 5.6+. All versions of phpseclib work all the way through PHP 7.4, as can be seen on the Travis CI test results:

    https://travis-ci.org/github/phpseclib/phpseclib

    (older versions of PHP aren't unit tested because Travis CI doesn't support them; Docker containers could be used but yeh)

    I am still fairly new to ssh but if I understand the above correctly, so long as the remote server has a .pub key I can simply supply my connection with my local private key (and user) and I should be able to connect? Does the public key need to be somewhere specific?

    Well with OpenSSH server the public key would need to live in ~/.ssh/authorized_keys. On the client end of things all you really need is the private key. The public key can be extracted from the private key.