# L4D2ServerTool **Repository Path**: wimi_ink/l4-d2-server-tool ## Basic Information - **Project Name**: L4D2ServerTool - **Description**: 求生之路2服务器管理工具(该项目为AI编写) - **Primary Language**: C# - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-21 - **Last Updated**: 2026-03-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # L4D2 Server Tool > 🎮 求生之路 2(Left 4 Dead 2)服务器管理工具 - 跨平台 Web API 控制 [![.NET](https://img.shields.io/badge/.NET-10.0-512BD4?style=flat&logo=dotnet)](https://dotnet.microsoft.com/) [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-lightgrey?style=flat)](https://github.com/) [![License](https://img.shields.io/badge/license-MIT-green?style=flat)](LICENSE) --- ## 📖 简介 **L4D2 Server Tool** 是一个基于 .NET 10 的跨平台服务器管理工具,提供 RESTful API 来控制《求生之路 2》专用服务器(srcds)。支持 Windows 和 Linux 系统,可通过 Web API 或 Python 客户端远程管理服务器。 ### ✨ 主要功能 - 🚀 **服务器控制** - 启动、停止、重启 L4D2 服务器 - 📊 **状态监控** - 实时查看服务器状态、玩家数量、运行时长 - 💬 **命令发送** - 通过 API 发送控制台命令到服务器 - 📝 **日志管理** - 获取服务器日志、清除日志 - 📁 **文件浏览** - 查看服务器相关文件 - 🔐 **API 安全** - 支持 API Key 验证 - 🔄 **自动重启** - 服务器崩溃后自动重启 - 🌐 **跨平台** - Windows 和 Linux 完美支持 --- ## 🚀 快速开始 ### 前置要求 - ✅ .NET 10.0 SDK - ✅ L4D2 专用服务器文件(srcds_run / srcds.exe) - ✅ Python 3.x(可选,用于 Python 客户端) ### 1. 克隆项目 ```bash git clone https://gitee.com/your-username/l4d2-server-tool.git cd l4d2-server-tool ``` ### 2. 配置文件 编辑 `L4D2 Server Tool/appsettings.json`: ```json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:34002" } } }, "ApiKey": "your-secret-api-key-change-me", "WebPort": 34002, "Server": { "ExecutablePath": "/path/to/left4dead2/srcds_run", "Arguments": "-game left4dead2 +ip 0.0.0.0 +port 27015 +maxplayers 4", "WorkingDirectory": "/path/to/left4dead2", "AutoRestart": true, "AutoRestartDelaySeconds": 3 } } ``` ### 3. 启动服务 ```bash cd "L4D2 Server Tool" dotnet run ``` ### 4. 测试 API ```bash # 健康检查(不需要 API Key) curl http://localhost:34002/api/health # 获取服务器状态 curl -H "X-API-Key: your-secret-api-key" http://localhost:34002/api/status # 启动服务器 curl -H "X-API-Key: your-secret-api-key" -X POST http://localhost:34002/api/start ``` --- ## 📡 API 文档 ### 基础信息 - **基础 URL**: `http://:34002` - **认证方式**: Header `X-API-Key: ` 或 URL 参数 `?api_key=` - **数据格式**: JSON ### API 端点 | 方法 | 端点 | 描述 | 需要 API Key | |------|------|------|-------------| | `GET` | `/api/health` | 健康检查 | ❌ | | `GET` | `/api/status` | 获取服务器状态 | ✅ | | `POST` | `/api/start` | 启动服务器 | ✅ | | `POST` | `/api/stop` | 停止服务器 | ✅ | | `POST` | `/api/restart` | 重启服务器 | ✅ | | `POST` | `/api/command` | 发送控制台命令 | ✅ | | `GET` | `/api/logs` | 获取服务器日志 | ✅ | | `POST` | `/api/logs/clear` | 清除日志 | ✅ | | `GET` | `/api/files` | 获取文件列表 | ✅ | --- ### 请求示例 #### 1. 获取服务器状态 ```bash curl -H "X-API-Key: your-api-key" http://localhost:34002/api/status ``` **响应:** ```json { "success": true, "message": "Success", "code": 200, "data": { "isRunning": true, "processId": 12345, "startTime": "2026-03-23T15:00:00", "uptime": "01.02:30:45", "map": "c1m1_hotel", "playerCount": 4, "maxPlayers": 32, "gamePort": 27015, "webPort": 34002, "status": "Running", "restartCount": 0 } } ``` #### 2. 启动服务器 ```bash curl -H "X-API-Key: your-api-key" -X POST http://localhost:34002/api/start ``` **响应:** ```json { "success": true, "message": "Server started successfully", "code": 200 } ``` #### 3. 发送控制台命令 ```bash curl -H "X-API-Key: your-api-key" \ -X POST http://localhost:34002/api/command \ -H "Content-Type: application/json" \ -d '{"command": "status"}' ``` **响应:** ```json { "success": true, "message": "Command 'status' sent", "code": 200 } ``` #### 4. 获取日志 ```bash curl -H "X-API-Key: your-api-key" \ "http://localhost:34002/api/logs?count=10" ``` **响应:** ```json { "success": true, "message": "Success", "code": 200, "data": [ { "timestamp": "2026-03-23T15:30:00", "type": "OUTPUT", "message": "Server listening on 27015" }, { "timestamp": "2026-03-23T15:30:05", "type": "COMMAND", "message": "status" } ] } ``` #### 5. 获取文件列表 ```bash curl -H "X-API-Key: your-api-key" \ "http://localhost:34002/api/files?path=cfg" ``` **响应:** ```json { "success": true, "message": "Success", "code": 200, "data": [ { "name": "server.cfg", "path": "/path/to/cfg/server.cfg", "size": 1024, "lastModified": "2026-03-23T10:00:00", "isDirectory": false } ] } ``` --- ## 🐍 Python 客户端 ### 安装依赖 ```bash pip install requests ``` ### 使用示例 ```python from python_client import L4D2ServerClient # 初始化客户端 client = L4D2ServerClient( base_url="http://192.168.0.9:34002", api_key="your-secret-api-key" ) # 获取状态 status = client.get_status() print(f"服务器状态:{'运行中' if status['data']['isRunning'] else '已停止'}") # 启动服务器 client.start_server() # 发送命令 client.send_command("mp_gamemode versus") # 获取日志 logs = client.get_logs(count=10) for log in logs['data']: print(f"[{log['timestamp']}] {log['type']}: {log['message']}") # 停止服务器 client.stop_server() ``` ### 完整示例脚本 ```bash # 运行示例脚本 python python_client.py status python python_client.py start python python_client.py stop python python_client.py command "status" ``` --- ## ⚙️ 配置说明 ### appsettings.json | 配置项 | 说明 | 默认值 | 必填 | |--------|------|--------|------| | `ApiKey` | API 访问密钥 | `your-secret-api-key-change-me` | ✅ | | `WebPort` | Web API 端口 | `34002` | ✅ | | `Kestrel.Endpoints.Http.Url` | Kestrel 监听地址 | `http://0.0.0.0:34002` | ✅ | | `Server.ExecutablePath` | L4D2 服务器程序路径 | `./srcds_run` | ✅ | | `Server.Arguments` | L4D2 启动参数 | `""` | ❌ | | `Server.WorkingDirectory` | L4D2 工作目录 | `""` | ❌ | | `Server.AutoRestart` | 是否自动重启 | `true` | ❌ | | `Server.AutoRestartDelaySeconds` | 自动重启延迟(秒) | `3` | ❌ | ### L4D2 启动参数示例 ```json { "Server": { "Arguments": "-game left4dead2 +ip 0.0.0.0 +port 27015 +maxplayers 4 +map c1m1_hotel" } } ``` 常用参数: - `-game left4dead2` - 游戏名称 - `+ip 0.0.0.0` - 监听所有网卡 - `+port 27015` - 游戏端口 - `+maxplayers 4` - 最大玩家数 - `+map c1m1_hotel` - 初始地图 - `-insecure` - 禁用 VAC(开发用) --- ## 🔐 安全配置 ### 1. 修改默认 API Key ```json { "ApiKey": "生成一个强密码作为 API Key" } ``` **生成随机 API Key:** ```bash # Linux/Mac openssl rand -hex 32 # PowerShell -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEach-Object {[char]$_}) ``` ### 2. 防火墙配置 ```bash # Ubuntu/Debian sudo ufw allow 34002/tcp # CentOS/RHEL sudo firewall-cmd --add-port=34002/tcp --permanent sudo firewall-cmd --reload # Windows (PowerShell 管理员) New-NetFirewallRule -DisplayName "L4D2 Server Tool" -Direction Inbound -LocalPort 34002 -Protocol TCP -Action Allow ``` ### 3. 使用 HTTPS(生产环境推荐) ```json { "Kestrel": { "Endpoints": { "Https": { "Url": "https://0.0.0.0:34402", "Certificate": { "Path": "/path/to/cert.pfx", "Password": "cert-password" } } } } } ``` --- ## 🛠️ 开发指南 ### 构建项目 ```bash cd "L4D2 Server Tool" # Debug 构建 dotnet build # Release 构建 dotnet build -c Release # 发布(Windows) dotnet publish -c Release -r win-x64 --self-contained # 发布(Linux) dotnet publish -c Release -r linux-x64 --self-contained ``` ### 运行测试 ```bash dotnet test ``` ### 代码格式化 ```bash dotnet format ``` --- ## 📊 项目结构 ``` l4d2-server-tool/ ├── L4D2 Server Tool/ │ ├── Program.cs # 主程序入口 │ ├── Services/ │ │ └── ServerService.cs # 服务器管理服务 │ ├── Models/ │ │ └── Models.cs # 数据模型 │ ├── appsettings.json # 配置文件 │ └── L4D2_Server_Tool.csproj # 项目文件 ├── python_client.py # Python 客户端库 ├── .gitignore # Git 忽略规则 ├── CONTRIBUTING.md # 贡献指南 ├── README_START.md # 启动指南 └── README.md # 项目文档 ``` --- ## 🐛 故障排除 ### 1. 端口被占用 **错误:** `Address already in use` **解决:** ```bash # 查看端口占用 netstat -tlnp | grep 34002 # 或 lsof -i :34002 # 杀死占用端口的进程 kill -9 ``` ### 2. 找不到 L4D2 服务器程序 **错误:** `No such file or directory` **解决:** 检查 `appsettings.json` 中的 `ExecutablePath` 和 `WorkingDirectory` 是否正确。 ### 3. API Key 验证失败 **错误:** `Unauthorized: Invalid or missing API key` **解决:** 确保请求中包含正确的 API Key: ```bash curl -H "X-API-Key: your-correct-key" http://localhost:34002/api/status ``` ### 4. 命令发送失败 **错误:** `StandardIn has not been redirected` **解决:** 确保 `ServerService.cs` 中设置了 `RedirectStandardInput = true`。 ### 5. 输出延迟 **问题:** 日志输出有延迟 **解决:** 已优化为行缓冲模式,如仍有延迟,检查 `stdbuf` 参数是否正确。 --- ## 🤝 贡献 欢迎提交 Issue 和 Pull Request! 1. Fork 本项目 2. 创建功能分支 (`git checkout -b feature/AmazingFeature`) 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`) 4. 推送到分支 (`git push origin feature/AmazingFeature`) 5. 开启 Pull Request 详见 [CONTRIBUTING.md](CONTRIBUTING.md) --- ## 📄 许可证 本项目采用 MIT 许可证 - 详见 [LICENSE](LICENSE) 文件 --- ## 🙏 致谢 - [Valve Corporation](https://www.valvesoftware.com/) - Left 4 Dead 2 - [.NET Team](https://dotnet.microsoft.com/) - .NET 10 - 所有贡献者和使用者 --- ## 📬 联系方式 - 📧 Email: your-email@example.com - 💬 Issues: [GitHub Issues](https://github.com/your-username/l4d2-server-tool/issues) - 🌐 主页:[项目主页](https://github.com/your-username/l4d2-server-tool) ---
**Made with ❤️ by OpenClaw** 如果这个项目对你有帮助,请给一个 ⭐ Star!