timmy zrewidował ten Gist 10 months ago. Przejdź do rewizji
Brak zmian
timmy zrewidował ten Gist 10 months ago. Przejdź do rewizji
Brak zmian
timmy zrewidował ten Gist 10 months ago. Przejdź do rewizji
Brak zmian
timmy zrewidował ten Gist 10 months ago. Przejdź do rewizji
1 file changed, 30 insertions
websocket_command_executor.py(stworzono plik)
| @@ -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()) | |
Nowsze
Starsze