agosh commited on
Commit
6118034
·
verified ·
1 Parent(s): bdc51e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -4
app.py CHANGED
@@ -1,8 +1,54 @@
1
- from fastapi import FastAPI
 
 
 
 
 
 
2
 
3
  app = FastAPI()
4
 
5
- @app.get("/")
6
- def greet_json():
7
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
1
+ import os
2
+ import asyncio
3
+ import pty
4
+ import subprocess
5
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
6
+ from fastapi.responses import HTMLResponse
7
+ from fastapi.middleware.cors import CORSMiddleware
8
 
9
  app = FastAPI()
10
 
11
+ # Permitir CORS para qualquer origem
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ @app.websocket("/ws")
20
+ async def websocket_endpoint(websocket: WebSocket):
21
+ await websocket.accept()
22
+
23
+ # Cria um pseudo-terminal com bash
24
+ pid, fd = pty.fork()
25
+
26
+ if pid == 0:
27
+ # Processo filho: executa o shell
28
+ shell = os.environ.get("SHELL", "/bin/bash")
29
+ os.execvp(shell, [shell])
30
+ else:
31
+ loop = asyncio.get_event_loop()
32
+
33
+ async def read_from_terminal():
34
+ while True:
35
+ try:
36
+ data = await loop.run_in_executor(None, os.read, fd, 1024)
37
+ if data:
38
+ await websocket.send_text(data.decode(errors="ignore"))
39
+ except Exception as e:
40
+ print("Erro ao ler do terminal:", e)
41
+ break
42
+
43
+ async def write_to_terminal():
44
+ try:
45
+ while True:
46
+ msg = await websocket.receive_text()
47
+ os.write(fd, msg.encode())
48
+ except WebSocketDisconnect:
49
+ print("Cliente desconectado")
50
+ os.close(fd)
51
+
52
+ # Executa leitura e escrita concorrentes
53
+ await asyncio.gather(read_from_terminal(), write_to_terminal())
54