有些小伙伴想自己搭建一个在线版的php框架然后实现ssh的自动连接,并且还能自定义输入命令信息,然后自动执行ssh命令的效果,通过php+html页面即可实现,但是前提你需要安装好SSH2 扩展,否则它会提示“SSH2 扩展没有安装或启用”的字样,具体怎么弄呢,下面是源码。
<?php
// 检查 SSH2 函数是否可用
if (function_exists('ssh2_connect')) {
// 连接信息
$host = 'your-ssh-server.com'; // SSH 服务器地址
$port = 22; // SSH 服务器端口
$username = 'your-username'; // SSH 用户名
$password = 'your-password'; // SSH 密码
// 建立 SSH 连接
$connection = ssh2_connect($host, $port);
if ($connection) {
// 尝试认证
if (ssh2_auth_password($connection, $username, $password)) {
// 认证成功,执行命令
$command = 'ls -l'; // 这里写你要执行的 SSH 命令
$stream = ssh2_exec($connection, $command);
// 等待命令执行完毕并获取输出
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);
fclose($stream);
// 输出执行结果
echo $output;
} else {
echo 'SSH 认证失败';
}
} else {
echo 'SSH 连接失败';
}
} else {
echo 'SSH2 扩展没有安装或启用';
}
?>
下面是我自己上传到服务器的目录试了一下,发现提示“SSH2 扩展没有安装或启用”,这时候我们需要做的就是把SSH2 扩展安装一下就可以了。
|