linux安裝ssh2,php遠端登入伺服器
1:安裝libssh2
wget http://www.libssh2.org/download/libssh2-1.4.2.tar.gz
tar -xzvf libssh2-1.4.2.tar.gz
cd libssh2-1.4.2
./configure --prefix=/vol/usr/local/lamp/libssh2 (libssh2的安裝目錄)
make
make install
2:安裝ssh2
wget http://pecl.php.net/package/ssh2
tar -xzvf ssh2-0.13.tgz
cd ssh2-0.13
wget http://pecl.php.net/get/ssh2-0.13.tgz
tar zxvf ssh2-0.13.tgz
phpize
./configure --with-php-config=/usr/local/php/bin/php-config --prefix=/vol/usr/local/lamp/ssh2 --with-ssh2=/vol/usr/local/lamp/libssh2
make
make install
在php.ini配置檔案中新增ssh2擴充套件:extension=ssh2.so
參考連結:https://my.oschina.net/u/2505940/blog/1587767
/**
* 遠端登陸伺服器
*/
private function remote_login($cmd='', $config=[]) {
if (empty($config)) {
return false;
}
// 連線伺服器
$connection=ssh2_connect($config['host'], $config['port']);
// 身份驗證
ssh2_auth_password($connection, $config['username'], $config['password']);
// 執行命令
$ret=ssh2_exec($connection, $cmd);
// 獲取結果
stream_set_blocking($ret, true);
// 返回結果
return stream_get_contents($ret);
}
/**
* 遠端操作伺服器
*/
public function test() {
$config['host'] = 'xxx'; //伺服器的ip
$config['port'] = 22;
$config['username'] = 'root'; //使用者名稱
$config['password'] = 'xxxx'; //密碼
$cmd = 'cd /&&ls';
$res = $this->remote_login($cmd, $config);
echo "<pre>";var_dump($res);
}