php利用ssh2组件执行其它服务器shell

环境:php7.3+

用php来登录ssh

就像本地的putty一样

安装两部分

SSH2模块的安装

查看最新版本

https://www.libssh2.org/

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

php组件

查看最新版本

https://pecl.php.net/package/ssh2

wget http://pecl.php.net/get/ssh2-1.3.1.tgz
tar -zxvf ssh2-1.3.1.tgz
cd ssh2-1.3.1
/usr/local/zend/bin/phpize
./configure --prefix=/usr/local/ssh2 --with-ssh2=/usr/local/libssh2 --with-php-config=/usr/local/zend/bin/php-config
make && make install

修改php.ini

extension=ssh2.so

Ubuntu下可以直接安装:

apt-get install libssh2-1 libssh2-1-dev php7.3-ssh2

用户名密码方式登录

$user="root";//远程用户名
$pass="******";//远程密码
$connection=ssh2_connect('10.10.10.10',22);
ssh2_auth_password($connection,$user,$pass);

用sshkey方式登录

$connection=ssh2_connect('10.10.10.10',22);
if(ssh2_auth_pubkey_file($connection, 'root', '/home/id_rsa.pub', '/home/id_rsa', 'secret'))
{
echo "Public Key Authentication Successful\n";
} else {
die('Public Key Authentication Failed');
}

执行命令并得到返回值

$cmd="ps aux";//命令
$ret=ssh2_exec($connection,$cmd);
stream_set_blocking($ret, true);
echo (stream_get_contents($ret));

windows版本编译libssh2

https://www.libssh2.org/snapshots/

下载源码解压,然后用 VS2017(任何版本) 打开 libssh2\win32\libssh2.dsw

属性管理器中选择dll版本编译

或者从以下网址下载

https://pecl.php.net/package/ssh2/1.3.1/windows

windows参考

https://blog.csdn.net/xiaoting451292510/article/details/89459057

linux参考

https://ptp5.com/archives/73.html

https://www.php.cn/php-weizijiaocheng-434441.html

https://www.liangzl.com/get-article-detail-38429.html

https://zhuanlan.zhihu.com/p/67064183

https://blog.csdn.net/u011198997/article/details/80653120

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注