import asyncio import websockets import subprocess async def handle_command(websocket, path): try: async for message in websocket: print(f"Received command: {message}") # 執行系統指令 try: result = subprocess.check_output(message, shell=True, stderr=subprocess.STDOUT, text=True) except subprocess.CalledProcessError as e: result = f"Error executing command:\n{e.output}" # 回傳執行結果 await websocket.send(result) except websockets.exceptions.ConnectionClosed: print("Connection closed") except Exception as e: print(f"Unexpected error: {e}") # 啟動 WebSocket Server async def main(): server = await websockets.serve(handle_command, "0.0.0.0", 8765) print("WebSocket server started on ws://0.0.0.0:8765") await server.wait_closed() if __name__ == "__main__": asyncio.run(main())