php通过拓展ssh2控制linux

来源:互联网 发布:2016中国对外投资数据 编辑:程序博客网 时间:2024/05/27 19:27

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、安装支持库文件
[html] view plain copy
  1. yum install  php-devel php-pear libssh2 libssh2-devel -y  
直接登录SSH客户端,然后执行命令回车,安装需要的库文件。

2、安装SSH2扩展

[html] view plain copy
  1. pecl install -f ssh2  

执行命令,然后看到一个输入界面,直接回车。

安装SSH2扩展回车之后自动安装。

Linux CentOS环境安装PHP SSH2扩展过程记录

3、修改ssh2.ini

[html] view plain copy
  1.     touch /etc/php.d/ssh2.ini  
  2.   
  3.     echo extension=ssh2.so > /etc/php.d/ssh2.ini  
  4.   
  5. 添加文件进去。  


4、检查SSH2是否安装成功

[html] view plain copy
  1. php -m | grep ssh2  
  2.   
  3. php -i|grep ssh2  

Linux CentOS环境安装PHP SSH2扩展过程记录
这里,我们可以看到老左上面安装的SSH2扩展已经完毕且成功的。


php控制linux代码示例(控制mariadb服务的开启关闭):

[html] view plain copy
  1. <?php  
  2. header("content-type:text/html;charset=utf8");  
  3. $str="systemctl status mariadb.service ";  
  4. $host='192.168.1.59';//被控制的linux的ip  
  5. $user='root';//用户名  
  6. $passwd='123456';//密码  
  7. // 链接远程服务器  
  8. $connection = ssh2_connect($host, 22);  
  9. /*if (!$connection) die('connection to '.$host.':22 failed');  
  10. echo 'connection OK<br/>';*/  
  11. // 获取验证方式并打印  
  12. $auth_methods = ssh2_auth_none($connection, $user);  
  13. if (in_array('password', $auth_methods ))  
  14. {  
  15.     // 通过password方式登录远程服务器  
  16.     if (ssh2_auth_password($connection, $user, $passwd))  
  17.     {  
  18.         /*echo $user.' login OK<br/>';*/  
  19.         $stream = ssh2_exec($connection, $str); // 执行php  
  20.         $pwd=stream_set_blocking($stream, true);  
  21.         // 获取执行pwd后的内容  
  22.         $pwd1=stream_get_contents($stream);  
  23.         print_r($pwd1);  
  24.         $a=strpos($pwd1,'running');  
  25.         if($a)  
  26.         {  
  27.             $b='running';  
  28.             $st="systemctl stop mariadb.service";  
  29.         }else  
  30.         {  
  31.             $b='dead';  
  32.             $st="systemctl start mariadb.service";  
  33.         }  
  34.         $stream = ssh2_exec($connection, $st); // 执行php  
  35.         /* $pwd=stream_set_blocking($stream, true); // 获取执行pwd后的内容  
  36.          if ($stream === FALSE) die("pwd failed");  
  37.          echo 'pwd: '.stream_get_contents($stream).'<br/>';*/  
  38.     }  
  39.     else  
  40.     {  
  41.         die( $user.' login Failed<br/>');  
  42.     }  
  43. }  
  44. if($b=='dead')  
  45. {  
  46.     echo  "服务器状态:".$b."<a href='a.php'>开启</a>";  
  47. }else  
  48. {  
  49.     echo  "服务器状态:".$b."<a href='a.php'>关闭</a>";  
  50. }  
0 0
原创粉丝点击