php 实现ssh
PHP 实现 SSH 连接
在 PHP 中实现 SSH 连接通常可以通过扩展库或第三方工具完成。以下是几种常见的方法:
使用 phpseclib 库
phpseclib 是一个纯 PHP 实现的 SSH 库,支持 SSH2、SFTP 等功能。安装后可通过以下代码建立 SSH 连接:

require_once 'phpseclib/Net/SSH2.php';
$ssh = new Net_SSH2('hostname');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('ls -la');
使用 SSH2 扩展
PHP 的 SSH2 扩展提供了原生 SSH 功能。需确保服务器已安装该扩展:

$connection = ssh2_connect('hostname', 22);
if (!ssh2_auth_password($connection, 'username', 'password')) {
exit('Authentication Failed');
}
$stream = ssh2_exec($connection, 'ls -la');
stream_set_blocking($stream, true);
echo stream_get_contents($stream);
使用系统命令
通过 exec() 或 shell_exec() 调用系统 SSH 命令(需服务器支持):
$output = shell_exec('ssh username@hostname "ls -la"');
echo $output;
注意事项
- 确保服务器已安装必要的扩展(如 SSH2)。
- 使用 phpseclib 时需包含正确的库路径。
- 密码认证存在安全风险,建议使用密钥认证。
- 错误处理应完善,避免暴露敏感信息。
密钥认证示例
使用 phpseclib 进行密钥认证:
require_once 'phpseclib/Net/SSH2.php';
require_once 'phpseclib/Crypt/RSA.php';
$key = new Crypt_RSA();
$key->loadKey(file_get_contents('private_key'));
$ssh = new Net_SSH2('hostname');
if (!$ssh->login('username', $key)) {
exit('Login Failed');
}
echo $ssh->exec('whoami');






