一、php扩展ssh2安装
①安装libssh2:
a. # cd /home/spider/lamp/
b. # wget http://www.libssh2.org/download/libssh2-1.2.8.tar.gz
c. # tar -zxvf libssh2-1.1.tar.gz
d. # cd libssh2-1.1
e. # ./configure --prefix=/home/spider/lamp/libssh2
f. # make all install
②Compiling libssh2 PHP Extension
a. # wget http://pecl.php.net/get/ssh2-0.11.0.tgz
b. # tar -zxvf ssh2-0.11.0.tgz
c. # cd ssh2-0.11.0
d. # phpize && ./configure –with-ssh2=/home/spider/lamp/libssh2 && make
# cp ./modules/ssh2.so /usr/lib/php/modules/ssh2.so
e. cp ./modules/ssh2.so ../../php5/lib/php/extensions/no-debug-non-zts-20060613/
f. 修改php.ini,添加 extension=ssh2.so
# service httpd restart
二、php ssh2使用示例
function getLogBySSH($location, $username, $userpwd, $cmd)
{
$ret = '';
if (!function_exists("ssh2_connect")) {
$ret = "function ssh2_connect() doesn't exist.\n";
return $ret;
}
if (!($conn = ssh2_connect($location, 22))){
$ret = "fail: unable to establish connection.\n";
return $ret;
}
if (!ssh2_auth_password($conn, $username, $userpwd)) {
$ret = "Authentication Fail.\n";
return $ret;
}
if (!($stream = ssh2_exec($conn, $cmd)) ){
$ret = "ssh2_exec() Fail.\n";
return $ret;
} else {
stream_set_blocking($stream, true);
//按字节数读取数据
while($buf = fread($stream, 4096) ){
$ret .= $buf;
}
/*
//按行读取数据
$nCount = 0;
while($buf = fgets($stream, 4096) ){
$nCount ++;
$ret .= $buf;
if ($nCount > 100) {
break;
}
}
*/
}
fclose($stream);
return $ret;
}