官方文档:

https://www.php.net/manual/zh/book.ssh2.php

第三方扩展库需要自己安装:

官方文档:

https://www.php.net/manual/zh/ssh2.installation.php

安装OpenSSL:

yum install -y openssl openssl-devel

编译安装 libssh2:

wget https://www.libssh2.org/download/libssh2-1.8.0.tar.gz
tar xvf libssh2-1.8.0.tar.gz
cd libssh2-1.8.0
./configure --prefix=/usr/local/libssh2
make
make install

编译安装 ssh2:

wget http://pecl.php.net/get/ssh2-0.13.tgz
tar xvf ssh2-0.13.tgz 
cd ssh2-0.13
phpize #没有的话 yum install php-devel ubuntu apt-get install php7.0-dev
./configure --prefix=/usr/local/ssh2 --with-ssh2=/usr/local/libssh2
make 
make install

修改配置:

vim /etc/php.ini
extension=ssh2.so

查看php是否已经包含ssh2模块:

php -m | grep ssh2
ssh2

或者使用pecl安装:

使用示例:更多示例详见官方文档。

<?php
$conn = ssh2_connect($host,22);

if(!ssh2_auth_password($conn,"root",$password)){
    die('Authentication Failed...');
}
$stream = ssh2_exec($conn , "ls -al");
$errorStream = ssh2_fetch_stream($stream,SSH2_STREAM_STDERR);

stream_set_blocking($stream, true);
stream_set_blocking($errorStream, true);

echo stream_get_contents($stream);
echo stream_get_contents($errorStream);

fclose($stream);
fclose($errorStream);