Home > database >  Message: Class 'PublicKeyLoader' not found (phpseclib)
Message: Class 'PublicKeyLoader' not found (phpseclib)

Time:03-12

I am trying to connect SSH to EC2 server with privatekey using php (phpseclib). I've downloaded phpseclib from GitHub and added into libraries folder.

My code:

/* $dir --- contains my library folder path */
include($dir.'phpseclib3/Net/SSH2.php');
include($dir.'phpseclib3/Crypt/PublicKeyLoader.php');
$key = new PublicKeyLoader();
$key->loadPrivateKey(file_get_contents($ppkpath));

$ssh = new SSH2('ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com');
if (!$ssh->login('ec2-user', $key)) {
    exit('Login Failed');
}

while executing this I got the following error

Class 'PublicKeyLoader' not found

CodePudding user response:

You don't load the namespace.

$key = new phpseclib3\Crypt\PublicKeyLoader();

Better would it be if you installed it with composer is that you include the composer autoloader.

include_once('vendor/autoload.php');

And then load the class in your current namespace with the use statement.

use phpseclib3\Crypt\PublicKeyLoader;

That way your code would become:

include_once('vendor/autoload.php');

use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Net\SSH2;

$key = new PublicKeyLoader();
$key->loadPrivateKey(file_get_contents($ppkpath));

$ssh = new SSH2('ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com');
if (!$ssh->login('ec2-user', $key)) {
    exit('Login Failed');
}

CodePudding user response:

I tried as @Tschallacka said. It works fine. But slightly I rechange the code as follows.

include_once('vendor/autoload.php');

use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Net\SSH2;

$key = PublicKeyLoader::loadPrivateKey(file_get_contents($ppkpath));

$ssh = new SSH2('ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com');
if (!$ssh->login('ec2-user', $key)) {
    exit('Login Failed');
}
  • Related