之前小杰写php程序时纠结过ssh2的安装问题,现在分享下经验:
Install PHP-SSH2 ( php-ssh ) extension
Install Build Dependancies
Shell
1
|
apt-get install libssh2-1 libssh2-1-dev
|
Download ssh2 files
Shell
1
2
3
|
cd /tmp
wget http://pecl.php.net/get/ssh2-0.12.tgz
tar -zxvf ssh2-0.12.tgz
|
Compile and Install
Shell
1
2
3
4
|
cd ssh2-0.12
phpize
./configure –with-ssh2
make && make install
|
Configure php-ssh2
Shell
1
|
echo -e “\n\n[php-ssh2]\n;http://pecl.php.net/package/ssh2\nextension=ssh2.so\n\n” >> /etc/php5/mods-available/ssh2.ini
|
Enable php-ssh2
Shell
1
|
ln -s /etc/php5/mods-available/ssh2.ini /etc/php5/conf.d/20-ssh2.ini
|
Restart PHP5-fpm to apply the config
Shell
1
|
service php5-fpm restart
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
二、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; } |