安装php ssh2扩展

本文目的

花了一下午时间,终于弄清楚了如何在php中使用libssh2扩展。在这个过程中遇到了一些问题,在解决问题的过程中加深了对php和ssh2的理解。所以,还是决定抽点时间回顾整个过程,作为备忘。

 

什么是php的ssh2扩展

Php ssh2扩(以下简称PECL/ssh2),允许在php程序中远程执行系统命令和文件传输,不需要在被监控的机器上单独开发和部署类似agnet的“木马”程序,大大降低了运维成本。

 

Php ssh2扩展需要的依赖库

  • openssl: 加密算法集合,C语言实现
  • libssh2:ssh2协议库库,C语言实现
  • PECL/ssh2: libssh2的php扩展,允许php程序调用libssh2中的函数

依赖关系:PECL/ssh2 –> libssh2 –> openssl

 

安装过程

[openssl]

$ cd openssl.x.x.x

$ ./configure --prefix=/your/openssl/home

$ make

$ make install

[libssh2]

$ cd libsshxxxx

$ ./configure --with-libssl-prefix=/your/openssl/home LIBS=-ldl

$ make

$ make install

PS: 配置中的“LIBS=-ldl”十分重要,如果不设置,如果不设置会导致“dlclose无法链接等错误”

 

[PECL/ssh2]

$ cd ssh2x.x.x

$ phpize

$ ./configure --with-php-config=/your/php/home/bin/php-config LIBS =-ldl

$ make

$ make install

$ vi php.ini

(添加extension=ssh2.so)

$ cp ssh2.so /php.ini/extention_dir

$ cd /apache/bin

$ apachectl restart (重启apache,使ssh2扩展生效)

$ php –I | grep ssh2 (检查PECL/ssh2是否安装成功,什么都没有标识没有成功)

PS: 配置中的“LIBS=-ldl”十分重要,如果不设置,会导致“libssh2 version >= 0.4 not found”错误,可以通过查看config.log,定位具体的bug位置,与安装libssh类似。

 

Php ssh2 API例子

通过PECL/ssh2相关API远程操作计算机时,首先需要获取链接,使用函数:

session ssh2_connect($host, $port)

获取链接后,需要进行验证,也就是登录,ssh2提供三种登入方式:

  • public key : 通过公钥和密钥进行验证,需要使用openssl生成工密钥,然后将公钥上传到需要远程访问机器的指定目录。特点比较安全,但是不太方便。PECL/ssh2支持。
  • password : 直接通过用户名和密码登录。特点是很方便,但是不安全,密码必须已明文的方式传给ssh2的api。PECL/ssh2支持。
  • keyboard-interactive:需要用户手动输入密码,PECL/ssh2不支持。

可以通过下面的api获取服务器提供的验证方式:

mixed ssh2_auth_none ( resource $session , string $username )

返回值是一个验证方式的字符串数组。

下面的代码演示password方式验证并在远程调用”pwd”命令:

<?php

$host='ip_or_host';

$user='some_user';

$passwd='your_password';

// 链接远程服务器

$connection = ssh2_connect($host, 36000);

if (!$connection) die('connection to '.$host.':3600 failed');

echo 'connection OK<br/>';

// 获取验证方式并打印

$auth_methods = ssh2_auth_none($connection, $user);

print_r( $auth_methods.'<br/>');

if (in_array('password', $auth_methods ))

{

    // 通过password方式登录远程服务器

    if (ssh2_auth_password($connection, $user, $passwd))

    {

        echo $user.' login OK<br/>';

        $stream = ssh2_exec($connection, "pwd"); // 执行php

        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/>');

    }

}

?>

总结

安装php扩展的一般过程:

1. phpize,生成配置文件和makefile等

2. ./configure && make && make install

3. 边界php.ini,添加extension

4. 将编译的so文件考到extension_dir目录下

5. 重启apche

6. 查看phpinfo或“php –i| grep xxxx”输出的页面中是否存需要安装的扩展

PS: 配置过程中,如果发现一些问题,可以通过查看config.log查看问题发生位置。

 

参考资料

posted @ 2012-02-06 15:06  bourneli  阅读(14066)  评论(3编辑  收藏  举报