当前位置: 代码网 > it编程>前端脚本>Python > Python结合Flask框架构建一个简易的远程控制系统

Python结合Flask框架构建一个简易的远程控制系统

2025年03月11日 Python 我要评论
1.概述随着信息化进程的加速,远程控制和系统管理工具越来越受到关注。尤其在企业环境中,管理员需要通过远程方式对计算机系统进行管理和维护。本文将详细介绍如何使用python与flask框架构建一个简易的

1.概述

随着信息化进程的加速,远程控制和系统管理工具越来越受到关注。尤其在企业环境中,管理员需要通过远程方式对计算机系统进行管理和维护。本文将详细介绍如何使用python与flask框架构建一个简易的远程控制系统。这个系统不仅能够远程执行操作命令(如关机、重启、锁屏等),还具备实时屏幕截图功能,适合用于学习与开发小型远程控制工具。

通过实现这一功能,我们不仅能够深入理解flask的使用,还能实践一些与操作系统交互的命令执行技术。本文还会讲解开发过程中遇到的一些技术难题,并分享如何进行修复和优化。

2.功能使用

双击运行exe文件运行后台服务,在浏览器中访问服务器中ip地址及固定端口,即可实现远程控制系统功能。

系统命令执行

本远程控制系统的核心功能是通过http请求来远程执行系统命令。具体包括以下操作:

关机与重启:

  • 使用windows自带的shutdown命令实现关机和重启功能。
  • shutdown /s /t 0:立即关机。
  • shutdown /r /t 0:立即重启。

锁屏:通过rundll32.exe user32.dll,lockworkstation命令锁定当前用户的屏幕。

清空回收站:使用powershell命令clear-recyclebin清空系统回收站。

禁用防火墙:通过reg add命令修改注册表,禁用windows防火墙服务。

删除休眠文件:通过powercfg -h off命令关闭系统休眠功能,从而删除休眠文件。

延迟window更新:通过更改注册表更改windows延迟最大天数到54321天来无限推迟windows更新,重启后生效。

win10右键/win11右键切换:无缝切换win11右键菜单风格以及恢复win10右键风格。

实时屏幕截图:使用pillow库的imagegrab.grab()方法截取当前屏幕,并通过flask返回给客户端。

关闭代理:

  • 使用vpn后电脑开机浏览器网页访问请求失败,可以试着点这个功能修复。
  • 每个功能都通过一个独立的路由实现,用户只需要点击对应按钮,系统就会在后台执行命令,并反馈操作结果。

实时屏幕监控

通过flask,我们实现了一个实时的屏幕监控功能。每3秒,客户端页面会请求一次服务器,获取当前屏幕的截图,并更新页面显示。这一功能对于远程桌面控制、设备监控等场景具有很大的应用潜力。

截图功能的实现依赖于pillow库的imagegrab.grab()方法,这是一个强大的图像捕获工具,适合在windows系统中截取当前屏幕。为了减少服务器的负担和网络带宽的压力,我们可以考虑对截图进行压缩处理,尤其是在高分辨率的环境下。

3. bug修复过程

在开发过程中,我们遇到了一些技术挑战,其中最主要的几个问题如下:

1. authorization认证失败

在实现api的认证时,我们通过在http请求的authorization头部传递api密钥进行验证。初步实现时,认证机制似乎工作正常,但我们发现有时即使api密钥正确,某些请求仍然无法通过验证。经检查,问题出在浏览器的缓存机制上。为了避免缓存带来的问题,我们修改了前端代码,在每次请求时动态更新请求url(通过添加时间戳),确保每次请求都是最新的。

2. 截图质量差

在实现屏幕截图功能时,我们发现直接返回截图时图片质量较差,尤其是在高分辨率屏幕上。为了解决这个问题,我们对图像进行无损压缩,以保持较高的图像质量,同时又不占用过多的带宽。

修复代码:

image.save(buffer, format='png')  # 无损png格式

通过这种方式,图像的质量得到了有效提升,且不会对性能造成过大影响。

3. 系统命令执行延迟

在执行系统命令时,尤其是涉及到重启、关机等操作,subprocess.run()方法可能会存在一定的延迟。这主要是因为执行这些命令会启动新的进程,导致主进程暂时阻塞。为了解决这个问题,我们采用了异步方式执行这些命令,避免了用户在执行命令时界面的卡顿。

修复代码:

subprocess.popen(command, shell=true)  # 异步执行命令

这种方式提高了响应速度,确保了系统在执行命令时能够流畅地响应其他请求。

4. 运行效果

服务端开启效果

手机浏览器端效果:

pc端浏览器效果:

5.相关源码

from flask import flask, render_template_string, request, jsonify, send_file
import subprocess
import os
import io
from pil import imagegrab, image

app = flask(__name__)

api_key = "your_secure_key_here"  # 替换成你的密钥

html_page = """
<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>远程控制系统</title>
    <style>
        body { font-family: arial, sans-serif; padding: 20px; background: #f4f4f4; }
        h2 { text-align: center; }
        .button-container { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 20px; }
        button { padding: 12px; border: none; background: #007bff; color: white; border-radius: 5px; cursor: pointer; }
        button:hover { background: #0056b3; }
        #status { text-align: center; margin-top: 20px; color: green; }
        #screenshot { display: block; margin: 20px auto; max-width: 100%; border: 1px solid #ccc; }
    </style>
</head>
<body>
    <h2>远程控制面板</h2>
    <div class="button-container">
        <button onclick="sendcommand('shutdown')">关机</button>
        <button onclick="sendcommand('reboot')">重启</button>
        <button onclick="sendcommand('lock_screen')">锁屏</button>
        <button onclick="sendcommand('clear_recycle_bin')">清空回收站</button>
        <button onclick="sendcommand('disable_firewall')">禁用防火墙</button>
        <button onclick="sendcommand('disable_proxy')">关闭代理</button>
        <button onclick="sendcommand('disable_hibernation')">删除休眠文件</button>
        <button onclick="sendcommand('delay_windows_update')">延迟更新</button>
        <button onclick="sendcommand('change_win10_context_menu')">win10右键菜单</button>
        <button onclick="sendcommand('restore_win11_context_menu')">win11右键菜单</button>
    </div>
    <h3>实时屏幕监控</h3>
    <button onclick="refreshscreenshot()">查看屏幕截图</button>
    <img id="screenshot" src="" alt="屏幕截图">
    <p id="status"></p>

    <script>
        function sendcommand(action) {
            fetch('/' + action, {
                method: 'post',
                headers: { 'authorization': 'bearer your_secure_key_here' }
            })
            .then(response => response.json())
            .then(data => document.getelementbyid("status").innertext = data.message)
            .catch(() => document.getelementbyid("status").innertext = "请求失败");
        }

        function refreshscreenshot() {
            const img = document.getelementbyid('screenshot');
            img.src = '/screenshot?time=' + new date().gettime();  // 防止缓存
        }

        setinterval(refreshscreenshot, 3000);  // 每3秒自动刷新截图
        window.onload = refreshscreenshot;    // 页面加载时刷新截图
    </script>
</body>
</html>
"""

# ----------------- 安全认证 -----------------
def check_auth():
    return request.headers.get("authorization", "") == f"bearer {api_key}"

# ----------------- 系统控制命令 -----------------
@app.route('/')
def home():
    return render_template_string(html_page)

@app.route('/shutdown', methods=['post'])
def shutdown():
    return run_command("shutdown /s /t 0", "关机命令已执行")

@app.route('/reboot', methods=['post'])
def reboot():
    return run_command("shutdown /r /t 0", "重启命令已执行")

@app.route('/lock_screen', methods=['post'])
def lock_screen():
    return run_command("rundll32.exe user32.dll,lockworkstation", "锁屏命令已执行")

@app.route('/clear_recycle_bin', methods=['post'])
def clear_recycle_bin():
    return run_command('powershell -command "clear-recyclebin -confirm:$false"', "回收站已清空")

@app.route('/disable_firewall', methods=['post'])
def disable_firewall():
    return run_command('reg add "hkey_local_machine\\system\\currentcontrolset\\services\\mpssvc" /v start /t reg_dword /d 4 /f', "防火墙已禁用")

@app.route('/disable_proxy', methods=['post'])
def disable_proxy():
    return run_command('reg add "hkey_current_user\\software\\microsoft\\windows\\currentversion\\internet settings" /v proxyenable /t reg_dword /d 0 /f', "全局代理已关闭")

@app.route('/disable_hibernation', methods=['post'])
def disable_hibernation():
    return run_command("powercfg -h off", "休眠文件已删除")

@app.route('/delay_windows_update', methods=['post'])
def delay_windows_update():
    cmd = 'reg add "hkey_local_machine\\software\\microsoft\\windowsupdate\\ux\\settings" /v "flightsettingsmaxpausedays" /t reg_dword /d 54321 /f'
    return run_command(cmd, "windows 更新已延迟")

@app.route('/change_win10_context_menu', methods=['post'])
def change_win10_context_menu():
    cmd = 'reg add "hkcu\\software\\classes\\clsid\\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\\inprocserver32" /f /ve & taskkill /f /im explorer.exe & start explorer.exe'
    return run_command(cmd, "win10 右键菜单已更改")

@app.route('/restore_win11_context_menu', methods=['post'])
def restore_win11_context_menu():
    cmd = 'reg delete "hkcu\\software\\classes\\clsid\\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}" /f & taskkill /f /im explorer.exe & start explorer.exe'
    return run_command(cmd, "win11 右键菜单已恢复")

# ----------------- 截图接口 (无压缩) -----------------
@app.route('/screenshot')
def screenshot():
    try:
        image = imagegrab.grab()
        buffer = io.bytesio()
        image.save(buffer, format='png')  # 无损png格式
        buffer.seek(0)
        return send_file(buffer, mimetype='image/png')
    except exception as e:
        return jsonify({"message": f"截图失败: {str(e)}"}), 500

# ----------------- 命令执行 -----------------
def run_command(command, success_message):
    if not check_auth():
        return jsonify({"message": "未授权"}), 401
    try:
        subprocess.run(command, shell=true, check=true)
        return jsonify({"message": success_message}), 200
    except exception as e:
        return jsonify({"message": f"操作失败: {str(e)}"}), 500

# ----------------- 启动 -----------------
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

6.总结

本文展示了如何使用python和flask构建一个简单的远程控制系统,能够远程执行系统命令、截图以及进行屏幕监控。通过这次开发实践,我们不仅熟悉了flask的使用,还深入了解了如何与操作系统交互,并处理一些常见的开发难题。

在开发过程中,我们不仅解决了认证、截图质量、命令延迟等问题,还深入了解了如何优化web应用的性能和用户体验。然而,值得注意的是,这个系统主要适用于windows操作系统,对于linux或mac用户,需要针对不同平台进行适配。

最后,虽然这个远程控制系统具备了基本的功能,但它依然存在一定的安全隐患。例如,api密钥的暴露可能导致不法分子进行恶意操作,因此在实际部署中,建议进一步加强安全机制(如使用oauth认证、数据加密等)。此外,考虑到大规模部署,系统的稳定性、性能以及扩展性也是我们需要关注的重点。

在未来的开发中,我们还可以考虑增加更多功能,如多用户管理、实时消息推送、操作记录日志等,使得系统更加完善和可靠。

以上就是python结合flask框架构建一个简易的远程控制系统的详细内容,更多关于python远程控制的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com