Last active 10 months ago

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

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

1 file changed, 30 insertions

websocket_command_executor.py(file created)

@@ -0,0 +1,30 @@
1 + import asyncio
2 + import websockets
3 + import subprocess
4 +
5 + async 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
24 + async 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 +
29 + if __name__ == "__main__":
30 + asyncio.run(main())
Newer Older