websocket_command_executor.py
· 955 B · Python
Originalformat
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())
| 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()) |