[php] PHP function ssh2_connect is not working

Following is my script:

    <?php
    $connection = ssh2_connect('XX.XX.XX.XX', 22);
    ssh2_auth_password($connection, 'root', '******');

    $stream = ssh2_exec($connection, 'useradd -d /home/users/test -m testftp');
    $stream = ssh2_exec($connection, 'passwd testftp');
    $stream = ssh2_exec($connection, 'password');
    $stream = ssh2_exec($connection, 'password');
    ?>

It showing the following error:

Fatal error: Call to undefined function ssh2_connect() in /home/chaosnz/public_html/fotosnap.net/test.php on line 2

How can I deal with this?

Thanks

This question is related to php ssh

The answer is


To expand on @neubert answer, if you are using Laravel 5 or similar, you can use phpseclib much simpler like this:

Run composer require phpseclib/phpseclib ~2.0

In your controller add

use phpseclib\Net\SSH2;

Then use it in a controller method like:

 $host = config('ssh.host');
 $username = config('ssh.username');
 $password = config('ssh.password'); 
 $command = 'php version';

 $ssh = new SSH2($host);
    if (!$ssh->login($username, $password)) {
        $output ='Login Failed';
    }
    else{
        $output = $ssh->exec($command);
 }

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road


If you are running a bomebrew on OSX, I used the following to install it:

brew install php56-ssh2

That worked for me. I pulled it from here. There should also be Ubuntu and OSX using mac port as well.


For WHM Panel

Menu > Server Configuration > Terminal:

yum install libssh2-devel -y

Menu > Software > Module Installers

  1. PHP PECL Manage Click
  2. ssh2 Install Now Click

Menu > Restart Services > HTTP Server (Apache)

Are you sure you wish to restart this service?

Yes

ssh2_connect() Work!


Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.


I have solved this on ubuntu 16.4 PHP 7.0.27-0+deb9u and nginx

sudo apt install php-ssh2 

I am running CentOS 5.6 as my development environment and the following worked for me.

su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini

/etc/init.d/httpd restart