简介
使用ssh2模块实现远程登录执行命令:
使用php ssh2模块可以在程序中远程执行命令,可以编写一些简单的脚本工具,实现集中管理
安装
1,安装libssh2库
从/下载源代码安装即可。
2,安装ssh2模块
从/package/ssh2下载源代码包,安装步骤:
/usr/local/php/bin/phpize
./configure --with-ssh2 && make
cp.libs/ssh2.so /data/php/lib/php/extensions/no-debug-non-zts-0613/
修改 php.ini 增加extension=ssh2.so
3,示例
$conn = ssh2_connect('192.168.1.2',22);
ssh2_auth_password($conn,usesrname,password);
$stream = ssh2_exec($conn,'/usr/local/bin/php-i');
stream_set_blocking($stream,true);
echo (stream_get_contents($stream));
$stream = ssh2_exec($conn,'ls');
stream_set_blocking($stream,true);
echo (stream_get_contents($stream));
ssh2的使用方式:
$connect=ssh2_connect("192.168.1.2",22);
ssh2_auth_password($connect,user,pass);
$stream=ssh2_exec($connect, "ls /home");
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);
fclose($stream);
echo $output ;
4,ssh2执行多个命令
第一个命令:
$ stream = ssh2_exec($ connection,'config global') ;
第二个命令:
$ stream = ssh2_exec($ connection,'get hardware cpu');
这样做:
$ stream = ssh2_exec($ connection,'command1; command2');
可以考虑使用ssh2_shell() 去解决 或者这样: ssh2_exec(cd/tmp&&tar-zvxfXXXYYY.x86_64.tgz)
参考链接:
/post/3790/