Python結(jié)合Flask框架構(gòu)建一個簡易的遠(yuǎn)程控制系統(tǒng)
1.概述
隨著信息化進(jìn)程的加速,遠(yuǎn)程控制和系統(tǒng)管理工具越來越受到關(guān)注。尤其在企業(yè)環(huán)境中,管理員需要通過遠(yuǎn)程方式對計(jì)算機(jī)系統(tǒng)進(jìn)行管理和維護(hù)。本文將詳細(xì)介紹如何使用Python與Flask框架構(gòu)建一個簡易的遠(yuǎn)程控制系統(tǒng)。這個系統(tǒng)不僅能夠遠(yuǎn)程執(zhí)行操作命令(如關(guān)機(jī)、重啟、鎖屏等),還具備實(shí)時屏幕截圖功能,適合用于學(xué)習(xí)與開發(fā)小型遠(yuǎn)程控制工具。
通過實(shí)現(xiàn)這一功能,我們不僅能夠深入理解Flask的使用,還能實(shí)踐一些與操作系統(tǒng)交互的命令執(zhí)行技術(shù)。本文還會講解開發(fā)過程中遇到的一些技術(shù)難題,并分享如何進(jìn)行修復(fù)和優(yōu)化。
2.功能使用
雙擊運(yùn)行exe文件運(yùn)行后臺服務(wù),在瀏覽器中訪問服務(wù)器中ip地址及固定端口,即可實(shí)現(xiàn)遠(yuǎn)程控制系統(tǒng)功能。
系統(tǒng)命令執(zhí)行
本遠(yuǎn)程控制系統(tǒng)的核心功能是通過HTTP請求來遠(yuǎn)程執(zhí)行系統(tǒng)命令。具體包括以下操作:
關(guān)機(jī)與重啟:
- 使用Windows自帶的shutdown命令實(shí)現(xiàn)關(guān)機(jī)和重啟功能。
- shutdown /s /t 0:立即關(guān)機(jī)。
- shutdown /r /t 0:立即重啟。
鎖屏:通過rundll32.exe user32.dll,LockWorkStation命令鎖定當(dāng)前用戶的屏幕。
清空回收站:使用PowerShell命令Clear-RecycleBin清空系統(tǒng)回收站。
禁用防火墻:通過REG ADD命令修改注冊表,禁用Windows防火墻服務(wù)。
刪除休眠文件:通過powercfg -h off命令關(guān)閉系統(tǒng)休眠功能,從而刪除休眠文件。
延遲window更新:通過更改注冊表更改windows延遲最大天數(shù)到54321天來無限推遲windows更新,重啟后生效。
win10右鍵/win11右鍵切換:無縫切換win11右鍵菜單風(fēng)格以及恢復(fù)win10右鍵風(fēng)格。
實(shí)時屏幕截圖:使用Pillow庫的ImageGrab.grab()方法截取當(dāng)前屏幕,并通過Flask返回給客戶端。
關(guān)閉代理:
- 使用VPN后電腦開機(jī)瀏覽器網(wǎng)頁訪問請求失敗,可以試著點(diǎn)這個功能修復(fù)。
- 每個功能都通過一個獨(dú)立的路由實(shí)現(xiàn),用戶只需要點(diǎn)擊對應(yīng)按鈕,系統(tǒng)就會在后臺執(zhí)行命令,并反饋操作結(jié)果。
實(shí)時屏幕監(jiān)控
通過Flask,我們實(shí)現(xiàn)了一個實(shí)時的屏幕監(jiān)控功能。每3秒,客戶端頁面會請求一次服務(wù)器,獲取當(dāng)前屏幕的截圖,并更新頁面顯示。這一功能對于遠(yuǎn)程桌面控制、設(shè)備監(jiān)控等場景具有很大的應(yīng)用潛力。
截圖功能的實(shí)現(xiàn)依賴于Pillow庫的ImageGrab.grab()方法,這是一個強(qiáng)大的圖像捕獲工具,適合在Windows系統(tǒng)中截取當(dāng)前屏幕。為了減少服務(wù)器的負(fù)擔(dān)和網(wǎng)絡(luò)帶寬的壓力,我們可以考慮對截圖進(jìn)行壓縮處理,尤其是在高分辨率的環(huán)境下。
3. BUG修復(fù)過程
在開發(fā)過程中,我們遇到了一些技術(shù)挑戰(zhàn),其中最主要的幾個問題如下:
1. Authorization認(rèn)證失敗
在實(shí)現(xiàn)API的認(rèn)證時,我們通過在HTTP請求的Authorization頭部傳遞API密鑰進(jìn)行驗(yàn)證。初步實(shí)現(xiàn)時,認(rèn)證機(jī)制似乎工作正常,但我們發(fā)現(xiàn)有時即使API密鑰正確,某些請求仍然無法通過驗(yàn)證。經(jīng)檢查,問題出在瀏覽器的緩存機(jī)制上。為了避免緩存帶來的問題,我們修改了前端代碼,在每次請求時動態(tài)更新請求URL(通過添加時間戳),確保每次請求都是最新的。
2. 截圖質(zhì)量差
在實(shí)現(xiàn)屏幕截圖功能時,我們發(fā)現(xiàn)直接返回截圖時圖片質(zhì)量較差,尤其是在高分辨率屏幕上。為了解決這個問題,我們對圖像進(jìn)行無損壓縮,以保持較高的圖像質(zhì)量,同時又不占用過多的帶寬。
修復(fù)代碼:
image.save(buffer, format='PNG') # 無損PNG格式
通過這種方式,圖像的質(zhì)量得到了有效提升,且不會對性能造成過大影響。
3. 系統(tǒng)命令執(zhí)行延遲
在執(zhí)行系統(tǒng)命令時,尤其是涉及到重啟、關(guān)機(jī)等操作,subprocess.run()方法可能會存在一定的延遲。這主要是因?yàn)閳?zhí)行這些命令會啟動新的進(jìn)程,導(dǎo)致主進(jìn)程暫時阻塞。為了解決這個問題,我們采用了異步方式執(zhí)行這些命令,避免了用戶在執(zhí)行命令時界面的卡頓。
修復(fù)代碼:
subprocess.Popen(command, shell=True) # 異步執(zhí)行命令
這種方式提高了響應(yīng)速度,確保了系統(tǒng)在執(zhí)行命令時能夠流暢地響應(yīng)其他請求。
4. 運(yùn)行效果
服務(wù)端開啟效果
手機(jī)瀏覽器端效果:
PC端瀏覽器效果:
5.相關(guān)源碼
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>遠(yuǎn)程控制系統(tǒng)</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>遠(yuǎn)程控制面板</h2> <div class="button-container"> <button onclick="sendCommand('shutdown')">關(guān)機(jī)</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')">關(guān)閉代理</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>實(shí)時屏幕監(jiān)控</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> """ # ----------------- 安全認(rèn)證 ----------------- def check_auth(): return request.headers.get("Authorization", "") == f"Bearer {API_KEY}" # ----------------- 系統(tǒng)控制命令 ----------------- @app.route('/') def home(): return render_template_string(HTML_PAGE) @app.route('/shutdown', methods=['POST']) def shutdown(): return run_command("shutdown /s /t 0", "關(guān)機(jī)命令已執(zhí)行") @app.route('/reboot', methods=['POST']) def reboot(): return run_command("shutdown /r /t 0", "重啟命令已執(zhí)行") @app.route('/lock_screen', methods=['POST']) def lock_screen(): return run_command("rundll32.exe user32.dll,LockWorkStation", "鎖屏命令已執(zhí)行") @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', "全局代理已關(guān)閉") @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 右鍵菜單已恢復(fù)") # ----------------- 截圖接口 (無壓縮) ----------------- @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 # ----------------- 命令執(zhí)行 ----------------- def run_command(command, success_message): if not check_auth(): return jsonify({"message": "未授權(quán)"}), 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.總結(jié)
本文展示了如何使用Python和Flask構(gòu)建一個簡單的遠(yuǎn)程控制系統(tǒng),能夠遠(yuǎn)程執(zhí)行系統(tǒng)命令、截圖以及進(jìn)行屏幕監(jiān)控。通過這次開發(fā)實(shí)踐,我們不僅熟悉了Flask的使用,還深入了解了如何與操作系統(tǒng)交互,并處理一些常見的開發(fā)難題。
在開發(fā)過程中,我們不僅解決了認(rèn)證、截圖質(zhì)量、命令延遲等問題,還深入了解了如何優(yōu)化Web應(yīng)用的性能和用戶體驗(yàn)。然而,值得注意的是,這個系統(tǒng)主要適用于Windows操作系統(tǒng),對于Linux或Mac用戶,需要針對不同平臺進(jìn)行適配。
最后,雖然這個遠(yuǎn)程控制系統(tǒng)具備了基本的功能,但它依然存在一定的安全隱患。例如,API密鑰的暴露可能導(dǎo)致不法分子進(jìn)行惡意操作,因此在實(shí)際部署中,建議進(jìn)一步加強(qiáng)安全機(jī)制(如使用OAuth認(rèn)證、數(shù)據(jù)加密等)。此外,考慮到大規(guī)模部署,系統(tǒng)的穩(wěn)定性、性能以及擴(kuò)展性也是我們需要關(guān)注的重點(diǎn)。
在未來的開發(fā)中,我們還可以考慮增加更多功能,如多用戶管理、實(shí)時消息推送、操作記錄日志等,使得系統(tǒng)更加完善和可靠。
以上就是Python結(jié)合Flask框架構(gòu)建一個簡易的遠(yuǎn)程控制系統(tǒng)的詳細(xì)內(nèi)容,更多關(guān)于Python遠(yuǎn)程控制的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
安裝pyhttpx解決ImportError: DLL load failed錯誤
這篇文章主要為大家介紹了安裝pyhttpx解決ImportError: DLL load failed錯誤,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Python中的簡寫操作(for、if簡寫、匿名函數(shù))
這篇文章主要介紹了Python中的簡寫操作(for、if簡寫、匿名函數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07Python多項(xiàng)式回歸的實(shí)現(xiàn)方法
這篇文章主要介紹了Python多項(xiàng)式回歸的實(shí)現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03Python中的True,False條件判斷實(shí)例分析
這篇文章主要介紹了Python中的True,False條件判斷的用法,實(shí)例分析了針對不同數(shù)據(jù)類型的條件判斷用法,具有一定參考借鑒價值,需要的朋友可以參考下2015-01-01Python爬蟲過程解析之多線程獲取小米應(yīng)用商店數(shù)據(jù)
這篇文章主要介紹了Python爬蟲過程解析之多線程獲取小米應(yīng)用商店數(shù)據(jù),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11