You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django中实现无刷新通过SSH启动Ubuntu虚拟机CSGO服务器

解决方案与技术方向说明

一、核心实现逻辑

  • 前端通过Ajax/Fetch发送请求到Django后端接口(实现无刷新交互)
  • Django后端作为中转,通过Python SSH库连接到Ubuntu虚拟机,执行CSGO服务器启动命令
  • 后端将执行结果返回给前端,前端展示状态

二、具体落地步骤

1. 后端实现(Django部分)

首先安装Python SSH客户端库paramiko:

pip install paramiko

编写处理SSH连接的视图函数:

# views.py
from django.http import JsonResponse
import paramiko

def start_csgo_server(request):
    if request.method == 'POST':
        # 虚拟机SSH配置
        ssh_host = '192.168.44.122'  # 内网用这个IP,外网切换为94.32.143.84
        ssh_port = 44
        ssh_user = 'test'
        ssh_password = 'test'
        command = './csgoserver start'

        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(hostname=ssh_host, port=ssh_port, username=ssh_user, password=ssh_password)
            
            stdin, stdout, stderr = ssh_client.exec_command(command)
            output = stdout.read().decode('utf-8')
            error = stderr.read().decode('utf-8')
            ssh_client.close()

            if error:
                return JsonResponse({'status': 'error', 'message': error})
            else:
                return JsonResponse({'status': 'success', 'message': output})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'})

配置接口路由:

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    # 其他路由...
    path('start-csgo/', views.start_csgo_server, name='start_csgo'),
]

2. 前端实现(HTML+JS)

添加按钮和异步请求脚本:

<button id="checkBtn">Check</button>
<div id="status"></div>

<script>
document.getElementById('checkBtn').addEventListener('click', function() {
    fetch('/start-csgo/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        const statusDiv = document.getElementById('status');
        if (data.status === 'success') {
            statusDiv.textContent = 'CSGO服务器启动成功:' + data.message;
            statusDiv.style.color = 'green';
        } else {
            statusDiv.textContent = '启动失败:' + data.message;
            statusDiv.style.color = 'red';
        }
    })
    .catch(error => {
        document.getElementById('status').textContent = '请求出错:' + error;
    });
});

// 获取Django CSRF令牌的辅助函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>

三、疑问解答

  1. Ajax是否仅支持同主机请求?
    不是,Ajax可以跨域请求,但受浏览器同源策略限制。你的场景中前端请求的是自身的Django后端(同主机127.0.0.1:8000),不存在跨域问题。需要明确:浏览器无法直接发起SSH连接,必须通过后端中转,这是唯一可行的路径。

  2. REST如何落地?
    你编写的start-csgo/接口就是一个简易的REST风格接口:用POST方法触发操作,返回JSON格式响应。要更规范的话:

  • 可以使用Django REST Framework(DRF)构建标准API,添加身份认证、请求校验等功能
  • 遵循REST语义,比如用POST触发启动操作,用GET接口查询服务器运行状态

四、学习内容建议

  • Python SSH操作:深入掌握paramiko的密钥登录、长连接、命令执行细节(生产环境建议用密钥替代密码)
  • Django接口开发:熟悉视图函数、路由配置,以及DRF的基础使用(用于复杂API场景)
  • 前端异步请求:熟练使用Fetch/Axios,理解Django的CSRF防护机制
  • 安全规范:生产环境禁止硬编码敏感信息,用环境变量存储;限制接口访问权限,避免命令注入风险

内容的提问来源于stack exchange,提问作者JDie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:15:43