php通过ssh2扩展控制linux,模拟阿里云web控制台

来源:互联网 发布:q扫雷软件 编辑:程序博客网 时间:2024/05/22 10:26

请先安装lamp之后才能继续:  http://blog.csdn.net/zph1234/article/details/51248124

0.这里是centos,如果是windows环境安装扩展就更简单了,下载dll文件,在php.ini中打开就行了,记得关闭selinux和firewalld

1.yum install libssh2 libssh2-devel php-devel gcc-c++

2.下载ssh2扩展,从http://pecl.php.net/package/ssh2

3.如果是php5安装ssh2-0.13扩展,php7安装1.0

cd ssh2-0.13/

/usr/bin/phpize 
./configure --with-php-config=/usr/bin/php-config LIBS=-ldl
make
make install

4. vi /etc/php.ini

加入extension=ssh2.so

5.重启apache

6.vi test.php

[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.   
  3. $host='127.0.0.1';  
  4.   
  5. $user='root';  
  6.   
  7. $passwd='123456';  
  8.   
  9. // 链接远程服务器  
  10.   
  11. $connection = ssh2_connect($host, 22);  
  12.   
  13. if (!$connectiondie('connection to '.$host.':22 failed');  
  14.   
  15. echo 'connection OK<br/>';  
  16.   
  17. // 获取验证方式并打印  
  18.   
  19. $auth_methods = ssh2_auth_none($connection$user);  
  20.   
  21. print_r( $auth_methods.'<br/>');  
  22.   
  23. if (in_array('password'$auth_methods ))  
  24. {  
  25.   
  26.     // 通过password方式登录远程服务器  
  27.   
  28.     if (ssh2_auth_password($connection$user$passwd))  
  29.   
  30.     {  
  31.   
  32.         echo $user.' login OK<br/>';  
  33.   
  34.         $stream = ssh2_exec($connection"pwd"); // 执行php  
  35.   
  36.         stream_set_blocking($stream, true); // 获取执行pwd后的内容  
  37.   
  38.          if ($stream === FALSE) die("pwd failed");  
  39.   
  40.         echo 'pwd: '.stream_get_contents($stream).'<br/>';  
  41.   
  42.     }  
  43.   
  44.     else  
  45.   
  46.     {  
  47.   
  48.         die$user.' login Failed<br/>');  
  49.   
  50.     }  
  51.   

0 0