create terminal cloud can access from browser
To upload files, please first save the app
import streamlit as st
import subprocess
import os
import sys
from streamlit_ace import st_ace
# Set page config
st.set_page_config(
page_title="Browser Terminal",
page_icon="💻",
layout="wide"
)
# Initialize session state
if "command_history" not in st.session_state:
st.session_state.command_history = []
if "current_directory" not in st.session_state:
st.session_state.current_directory = os.getcwd()
if "terminal_output" not in st.session_state:
st.session_state.terminal_output = [f"Welcome to Browser Terminal\nCurrent directory: {os.getcwd()}\n"]
def execute_command(command):
"""Execute a shell command and return the output"""
if not command.strip():
return ""
# Handle cd command separately
if command.strip().startswith("cd "):
path = command.strip()[3:].strip()
if not path:
path = os.path.expanduser("~")
try:
if path == "..":
new_dir = os.path.dirname(st.session_state.current_directory)
elif os.path.isabs(path):
new_dir = path
else:
new_dir = os.path.join(st.session_state.current_directory, path)
new_dir = os.path.abspath(new_dir)
if os.path.exists(new_dir) and os.path.isdir(new_dir):
st.session_state.current_directory = new_dir
os.chdir(new_dir)
return f"Changed directory to: {new_dir}"
else:
return f"Directory not found: {path}"
except Exception as e:
return f"Error changing directory: {str(e)}"
# Handle other commands
try:
# Set the working directory for the command
os.chdir(st.session_state.current_directory)
# Execute the command
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=30 # 30 second timeout
)
output = ""
if result.stdout:
output += result.stdout
if result.stderr:
output += f"Error: {result.stderr}"
return output if output else "Command executed successfully (no output)"
except subprocess.TimeoutExpired:
return "Command timed out (30 seconds limit)"
except Exception as e:
return f"Error executing command: {str(e)}"
def clear_terminal():
"""Clear the terminal output"""
st.session_state.terminal_output = [f"Terminal cleared\nCurrent directory: {st.session_state.current_directory}\n"]
# Title and description
st.title("💻 Browser Terminal")
st.markdown("A web-based terminal interface that runs in your browser")
# Create columns for layout
col1, col2 = st.columns([3, 1])
with col1:
# Current directory display
st.info(f"📁 Current Directory: `{st.session_state.current_directory}`")
# Command input
st.subheader("Command Input")
command = st.text_input(
"Enter command:",
key="command_input",
placeholder="ls, pwd, cat filename.txt, etc.",
help="Enter shell commands to execute. Type 'clear' to clear terminal output."
)
# Execute button
col_exec, col_clear = st.columns([1, 1])
with col_exec:
if st.button("Execute", type="primary", use_container_width=True):
if command:
# Add command to history
st.session_state.command_history.append(command)
# Handle special commands
if command.strip().lower() == "clear":
clear_terminal()
else:
# Execute the command
output = execute_command(command)
st.session_state.terminal_output.append(f"$ {command}")
st.session_state.terminal_output.append(output + "\n")
# Clear the input
st.rerun()
with col_clear:
if st.button("Clear Terminal", use_container_width=True):
clear_terminal()
st.rerun()
with col2:
# Command history
st.subheader("Command History")
if st.session_state.command_history:
for i, hist_cmd in enumerate(reversed(st.session_state.command_history[-10:])): # Show last 10 commands
if st.button(f"📝 {hist_cmd}", key=f"hist_{i}", help="Click to rerun this command"):
# Execute the historical command
st.session_state.command_history.append(hist_cmd)
if hist_cmd.strip().lower() == "clear":
clear_terminal()
else:
output = execute_command(hist_cmd)
st.session_state.terminal_output.append(f"$ {hist_cmd}")
st.session_state.terminal_output.append(output + "\n")
st.rerun()
else:
st.write("No command history yet")
# Terminal output display
st.subheader("Terminal Output")
# Display terminal output in a code block
terminal_content = "\n".join(st.session_state.terminal_output)
# Use st_ace for better terminal-like display
st_ace(
value=terminal_content,
language='text',
theme='monokai',
height=400,
auto_update=True,
readonly=True,
show_gutter=False,
show_print_margin=False,
wrap=True,
font_size=14,
key="terminal_display"
)
# Quick commands section
st.subheader("Quick Commands")
quick_commands = {
"List Files": "ls -la",
"Current Directory": "pwd",
"System Info": "uname -a" if sys.platform != "win32" else "systeminfo",
"Disk Usage": "df -h" if sys.platform != "win32" else "dir",
"Process List": "ps aux" if sys.platform != "win32" else "tasklist",
"Environment Variables": "env" if sys.platform != "win32" else "set"
}
cols = st.columns(3)
for i, (name, cmd) in enumerate(quick_commands.items()):
with cols[i % 3]:
if st.button(name, key=f"quick_{i}"):
# Execute quick command
st.session_state.command_history.append(cmd)
output = execute_command(cmd)
st.session_state.terminal_output.append(f"$ {cmd}")
st.session_state.terminal_output.append(output + "\n")
st.rerun()
# Safety notice
st.warning("⚠️ **Safety Notice**: This terminal has limited capabilities and runs with restricted permissions. Some commands may not work or may be blocked for security reasons. Commands have a 30-second timeout limit.")
# Footer
st.markdown("---")
st.markdown("💡 **Tips**: Use `cd` to navigate directories, `ls` or `dir` to list files, and `clear` to clear the terminal output.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?