Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, WebSocket | |
from fastapi.responses import HTMLResponse | |
import subprocess | |
app = FastAPI() | |
# HTML template for the terminal interface | |
index_html = """ | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Web Terminal</title> | |
<style> | |
/* Add CSS styles to customize the appearance of the terminal */ | |
</style> | |
</head> | |
<body> | |
<div id="terminal"></div> | |
<script> | |
const terminal = document.getElementById("terminal"); | |
const ws = new WebSocket("ws://" + window.location.host + "/terminal"); | |
ws.onmessage = function(event) { | |
terminal.innerText += event.data + "\\n"; | |
}; | |
function sendCommand() { | |
const command = prompt("Enter command:"); | |
ws.send(command); | |
} | |
</script> | |
</body> | |
</html> | |
""" | |
# Store active websocket connections | |
connections = [] | |
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 | |
async def index(): | |
return HTMLResponse(content=index_html, status_code=200) | |