0.下载ssh2扩展,从http://pecl.php.net/package/ssh2,有linux扩展包,也有windows的dll,如果是php5安装ssh2-0.13或0.12扩展,php7安装1.0
windows安装方法:
1. 解压完后,会有三个文件,libssh2.dll、php_ssh.dll、php_ssh2.pdb。
2. 将 php_ssh.dll、php_ssh2.pdb 放到你的 php 扩展目录下 php/ext/ 下。
3. 将libssh2.dll 复制到 c:/windows/system32 和 c:/windows/syswow64 各一份
4. php.ini中加入 extension=php_ssh2.dll
5. 重启IIS,即可使用php执行ssh连接操作了。
查看phpinfo(),是否有显示php_ssh2扩展加载成功。
linux下安装方法:
1、安装支持库文件
- yum install php-devel php-pear libssh2 libssh2-devel -y
直接登录SSH客户端,然后执行命令回车,安装需要的库文件。
2、安装SSH2扩展
执行命令,然后看到一个输入界面,直接回车。
回车之后自动安装。

3、修改ssh2.ini
- touch /etc/php.d/ssh2.ini
-
- echo extension=ssh2.so > /etc/php.d/ssh2.ini
-
- 添加文件进去。
4、检查SSH2是否安装成功
- php -m | grep ssh2
-
- php -i|grep ssh2
这里,我们可以看到老左上面安装的SSH2扩展已经完毕且成功的。
php控制linux代码示例(控制mariadb服务的开启关闭):
- <?php
- header("content-type:text/html;charset=utf8");
- $str="systemctl status mariadb.service ";
- $host='192.168.1.59';//被控制的linux的ip
- $user='root';//用户名
- $passwd='123456';//密码
- // 链接远程服务器
- $connection = ssh2_connect($host, 22);
- /*if (!$connection) die('connection to '.$host.':22 failed');
- echo 'connection OK<br/>';*/
- // 获取验证方式并打印
- $auth_methods = ssh2_auth_none($connection, $user);
- if (in_array('password', $auth_methods ))
- {
- // 通过password方式登录远程服务器
- if (ssh2_auth_password($connection, $user, $passwd))
- {
- /*echo $user.' login OK<br/>';*/
- $stream = ssh2_exec($connection, $str); // 执行php
- $pwd=stream_set_blocking($stream, true);
- // 获取执行pwd后的内容
- $pwd1=stream_get_contents($stream);
- print_r($pwd1);
- $a=strpos($pwd1,'running');
- if($a)
- {
- $b='running';
- $st="systemctl stop mariadb.service";
- }else
- {
- $b='dead';
- $st="systemctl start mariadb.service";
- }
- $stream = ssh2_exec($connection, $st); // 执行php
- /* $pwd=stream_set_blocking($stream, true); // 获取执行pwd后的内容
- if ($stream === FALSE) die("pwd failed");
- echo 'pwd: '.stream_get_contents($stream).'<br/>';*/
- }
- else
- {
- die( $user.' login Failed<br/>');
- }
- }
- if($b=='dead')
- {
- echo "服务器状态:".$b."<a href='a.php'>开启</a>";
- }else
- {
- echo "服务器状态:".$b."<a href='a.php'>关闭</a>";
- }