from fastapi import FastAPI, WebSocket
import subprocess
app = FastAPI()
# HTML template for the terminal interface
index_html = """
Web Terminal
"""
# Store active websocket connections
connections = []
@app.websocket("/terminal")
async def terminal(websocket: WebSocket):
await websocket.accept()
connections.append(websocket)
try:
while True:
data = await websocket.receive_text()
# Execute the command and send the result back to the client
result = await execute_command(data)
await websocket.send_text(result)
finally:
connections.remove(websocket)
async def execute_command(command: str) -> str:
try:
# Execute the command using subprocess
result = subprocess.check_output(command, shell=True, text=True)
except subprocess.CalledProcessError as e:
result = f"Error: {e.output}"
return result
@app.get("/")
async def index():
return index_html