php实现ssh
PHP 实现 SSH 连接的方法
使用 PHP 实现 SSH 连接可以通过扩展库或第三方工具完成。以下是几种常见的方法:
使用 SSH2 扩展(php-ssh2)
确保服务器已安装 php-ssh2 扩展。可以通过以下命令安装:
sudo apt-get install php-ssh2 # Debian/Ubuntu
sudo yum install php-ssh2 # CentOS/RHEL
示例代码:
$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$stream = ssh2_exec($connection, 'ls -la');
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);
echo $output;
} else {
echo "Authentication failed";
}
使用 phpseclib 库
phpseclib 是一个纯 PHP 实现的 SSH 库,无需安装扩展。通过 Composer 安装:
composer require phpseclib/phpseclib
示例代码:
require 'vendor/autoload.php';
use phpseclib3\Net\SSH2;
$ssh = new SSH2('hostname');
if (!$ssh->login('username', 'password')) {
exit('Login failed');
}
echo $ssh->exec('pwd');
使用系统命令调用
通过 exec() 或 shell_exec() 调用系统 SSH 客户端(如 OpenSSH):
$command = 'ssh username@hostname "ls -la"';
$output = shell_exec($command);
echo $output;
注意事项
- 使用 SSH2 扩展需要服务器支持,且性能较高。
- phpseclib 兼容性更好,但纯 PHP 实现可能性能稍低。
- 直接调用系统命令存在安全隐患,需严格过滤输入。
- 推荐使用密钥认证而非密码,提升安全性。
密钥认证示例(phpseclib)
use phpseclib3\Net\SSH2;
use phpseclib3\Crypt\PublicKeyLoader;
$ssh = new SSH2('hostname');
$key = PublicKeyLoader::load(file_get_contents('/path/to/private.key'));
if (!$ssh->login('username', $key)) {
exit('Login failed');
}






