Последняя активность 10 months ago

這段程式碼建立了一個 WebSocket 伺服器,允許遠端用戶端傳送指令,並在伺服器端執行該指令後回傳執行結果。適用於遠端系統管理、指令控制或測試環境中的即時互動,但因為直接執行來自用戶端的指令,需特別注意安全性風險,如權限控管與輸入驗證,以防止指令注入攻擊。

websocket_command_executor.py Исходник
1import asyncio
2import websockets
3import subprocess
4
5async def handle_command(websocket, path):
6 try:
7 async for message in websocket:
8 print(f"Received command: {message}")
9
10 # 執行系統指令
11 try:
12 result = subprocess.check_output(message, shell=True, stderr=subprocess.STDOUT, text=True)
13 except subprocess.CalledProcessError as e:
14 result = f"Error executing command:\n{e.output}"
15
16 # 回傳執行結果
17 await websocket.send(result)
18 except websockets.exceptions.ConnectionClosed:
19 print("Connection closed")
20 except Exception as e:
21 print(f"Unexpected error: {e}")
22
23# 啟動 WebSocket Server
24async def main():
25 server = await websockets.serve(handle_command, "0.0.0.0", 8765)
26 print("WebSocket server started on ws://0.0.0.0:8765")
27 await server.wait_closed()
28
29if __name__ == "__main__":
30 asyncio.run(main())