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
st.set_page_config(
page_title="Browser Terminal",
page_icon="đģ",
layout="wide"
)
st.title("đģ Browser Terminal")
st.markdown("A web-based terminal interface you can access from your browser")
# 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 'output_history' not in st.session_state:
st.session_state.output_history = []
# Display current directory
st.markdown(f"**Current Directory:** `{st.session_state.current_directory}`")
# Terminal interface
col1, col2 = st.columns([4, 1])
with col1:
command = st.text_input(
"Enter command:",
key="command_input",
placeholder="Type your command here (e.g., ls, pwd, echo 'hello')"
)
with col2:
execute_button = st.button("Execute", type="primary")
# Execute command
if execute_button and command:
try:
# Change to the current directory
original_cwd = os.getcwd()
os.chdir(st.session_state.current_directory)
# Handle cd command specially
if command.strip().startswith('cd '):
path = command.strip()[3:].strip()
if path == '':
path = os.path.expanduser('~')
elif path == '..':
path = os.path.dirname(st.session_state.current_directory)
elif not os.path.isabs(path):
path = os.path.join(st.session_state.current_directory, path)
if os.path.exists(path) and os.path.isdir(path):
st.session_state.current_directory = os.path.abspath(path)
output = f"Changed directory to: {st.session_state.current_directory}"
success = True
else:
output = f"Directory not found: {path}"
success = False
else:
# Execute other commands
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
cwd=st.session_state.current_directory
)
output = ""
if result.stdout:
output += result.stdout
if result.stderr:
output += result.stderr
success = result.returncode == 0
# Add to history
st.session_state.command_history.append(command)
st.session_state.output_history.append({
'command': command,
'output': output,
'success': success,
'directory': st.session_state.current_directory
})
# Restore original directory
os.chdir(original_cwd)
# Show success message
if success:
st.toast("Command executed successfully! â
")
else:
st.toast("Command execution failed! â")
except Exception as e:
st.session_state.output_history.append({
'command': command,
'output': f"Error: {str(e)}",
'success': False,
'directory': st.session_state.current_directory
})
st.toast("An error occurred! â")
os.chdir(original_cwd)
# Clear history button
if st.button("Clear History"):
st.session_state.command_history = []
st.session_state.output_history = []
st.toast("History cleared! đī¸")
st.rerun()
# Display command history and output
if st.session_state.output_history:
st.markdown("---")
st.subheader("Terminal Output")
# Create a terminal-like display
terminal_content = ""
for entry in st.session_state.output_history[-20:]: # Show last 20 commands
terminal_content += f"$ {entry['command']}\n"
if entry['output']:
terminal_content += f"{entry['output']}\n"
terminal_content += "\n"
# Use ace editor for syntax highlighting and better display
st_ace(
value=terminal_content,
language='sh',
theme='monokai',
key="terminal_output",
height=400,
auto_update=True,
wrap=True,
font_size=14,
show_gutter=True,
show_print_margin=False,
annotations=None,
markers=None,
readonly=True
)
# Sidebar with common commands
with st.sidebar:
st.header("Quick Commands")
quick_commands = [
"ls -la",
"pwd",
"whoami",
"date",
"ps aux",
"df -h",
"free -h",
"uname -a",
"python --version",
"pip list"
]
st.markdown("Click on any command to execute:")
for cmd in quick_commands:
if st.button(cmd, key=f"quick_{cmd}"):
st.session_state.command_input = cmd
st.rerun()
st.markdown("---")
st.header("File Browser")
# Simple file browser
try:
files = os.listdir(st.session_state.current_directory)
directories = [f for f in files if os.path.isdir(os.path.join(st.session_state.current_directory, f))]
regular_files = [f for f in files if os.path.isfile(os.path.join(st.session_state.current_directory, f))]
st.markdown("**Directories:**")
for directory in sorted(directories):
if st.button(f"đ {directory}", key=f"dir_{directory}"):
st.session_state.current_directory = os.path.join(st.session_state.current_directory, directory)
st.rerun()
st.markdown("**Files:**")
for file in sorted(regular_files):
st.markdown(f"đ {file}")
except Exception as e:
st.error(f"Error reading directory: {e}")
# Instructions
with st.expander("âšī¸ How to use this terminal"):
st.markdown("""
### Features:
- Execute shell commands directly in your browser
- Navigate directories with `cd` command
- View command history and output
- Quick access to common commands
- File browser in the sidebar
### Supported Commands:
- **Navigation**: `cd`, `pwd`, `ls`
- **File operations**: `cat`, `head`, `tail`, `find`
- **System info**: `whoami`, `date`, `uname`, `ps`, `df`
- **Python**: `python`, `pip`
- **Text processing**: `grep`, `sort`, `wc`
### Security Note:
This terminal runs in a sandboxed environment. Some system commands may be restricted for security reasons.
### Tips:
- Use the quick commands in the sidebar for common operations
- The file browser helps you navigate directories
- Command history is preserved during your session
""")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?