基于SSH2的PHP远程编译AMXMODX插件并上传面板方案问询
解决方案:通过SSH2远程编译AMXMODX插件并上传
完全可以通过PHP的SSH2扩展替换本地exec编译逻辑,实现远程编译后再上传到游戏服务器。以下是具体修改步骤和代码示例:
前置准备
- 确保PHP环境已安装
ext-ssh2扩展(可通过php -m | grep ssh2验证) - 远程编译机需部署AMXMODX编译器
amxxpc,并确认其可执行权限及路径(若不在系统环境变量中,需使用绝对路径) - 远程编译机需开放SSH端口,且PHP主机有权限连接
核心修改:替换本地编译为SSH2远程编译
1. SSH2连接与文件传输
先实现远程编译的核心流程:上传.sma到远程临时目录、执行编译命令、取回.amxx文件。
function compileAmxxViaSsh(string $smaLocalPath, string $remoteSshHost, int $remoteSshPort, string $remoteSshUser, string $remoteSshPass, string $remoteTempDir, string $amxxpcPath): ?string { // 建立SSH连接 $connection = ssh2_connect($remoteSshHost, $remoteSshPort); if (!$connection || !ssh2_auth_password($connection, $remoteSshUser, $remoteSshPass)) { error_log("SSH连接或认证失败"); return null; } // 生成临时文件名避免冲突 $fileName = basename($smaLocalPath); $remoteSmaPath = $remoteTempDir . '/' . $fileName; $remoteAmxxPath = str_replace('.sma', '.amxx', $remoteSmaPath); $localAmxxPath = str_replace('.sma', '.amxx', $smaLocalPath); // 上传本地.sma到远程临时目录 if (!ssh2_scp_send($connection, $smaLocalPath, $remoteSmaPath, 0644)) { error_log("上传.sma到远程服务器失败"); ssh2_disconnect($connection); return null; } // 执行远程编译命令 $compileCmd = escapeshellcmd("$amxxpcPath $remoteSmaPath -o $remoteAmxxPath"); $stream = ssh2_exec($connection, $compileCmd); stream_set_blocking($stream, true); $compileOutput = stream_get_contents($stream); fclose($stream); // 检查编译是否成功(amxxpc输出包含"Done."即为成功) if (strpos($compileOutput, "Done.") === false) { error_log("远程编译失败:" . $compileOutput); ssh2_exec($connection, "rm -f $remoteSmaPath"); ssh2_disconnect($connection); return null; } // 取回编译后的.amxx文件到本地 if (!ssh2_scp_recv($connection, $remoteAmxxPath, $localAmxxPath)) { error_log("下载.amxx文件失败"); ssh2_exec($connection, "rm -f $remoteSmaPath $remoteAmxxPath"); ssh2_disconnect($connection); return null; } // 清理远程临时文件 ssh2_exec($connection, "rm -f $remoteSmaPath $remoteAmxxPath"); ssh2_disconnect($connection); return $localAmxxPath; }
2. 整合原有逻辑
将原有的本地编译调用替换为上述远程编译函数,之后保留你已有的SFTP上传到游戏服务器面板、插件配置写入逻辑即可:
// 示例调用 $smaFile = '/path/to/your/plugin.sma'; $remoteCompileConfig = [ 'host' => '远程编译机IP', 'port' => 22, 'user' => 'ssh用户名', 'pass' => 'ssh密码', 'temp_dir' => '/tmp/amxx_compile', 'amxxpc_path' => '/usr/local/amxmodx/scripting/amxxpc' // 编译器绝对路径 ]; // 远程编译 $amxxFile = compileAmxxViaSsh( $smaFile, $remoteCompileConfig['host'], $remoteCompileConfig['port'], $remoteCompileConfig['user'], $remoteCompileConfig['pass'], $remoteCompileConfig['temp_dir'], $remoteCompileConfig['amxxpc_path'] ); if ($amxxFile) { // 执行原有SFTP上传到游戏服务器面板逻辑 yourExistingSftpUploadFunction($amxxFile); // 执行原有插件配置写入逻辑 yourExistingConfigWriteFunction(); }
注意事项
- 优先使用SSH密钥认证替代密码认证,避免明文密码泄露,可将
ssh2_auth_password替换为ssh2_auth_pubkey_file - 远程临时目录需确保SSH用户有读写权限,建议使用
/tmp这类公共临时目录 - 捕获并处理编译输出中的错误信息,方便排查问题
- 若远程编译机为Linux系统,注意路径分隔符使用
/,Windows则用\(需转义) - 可添加连接超时、重试机制提升稳定性
内容的提问来源于stack exchange,提问作者gorkem
相关产品推荐
相关产品推荐

