-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbash_runner.py
More file actions
230 lines (196 loc) · 6.6 KB
/
Copy pathbash_runner.py
File metadata and controls
230 lines (196 loc) · 6.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import streamlit as st
import subprocess
import sys
from datetime import datetime
# Set page configuration
st.set_page_config(
page_title="Bash Command Runner",
page_icon="🖥️",
layout="wide"
)
# Initialize session state for command history
if 'command_history' not in st.session_state:
st.session_state.command_history = []
# Title and description
st.title("🖥️ Bash Command Runner")
st.markdown("Enter bash commands in the text box below and click 'Run Commands' to execute them.")
# Create two columns for better layout
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("📝 Command Input")
# Large text area for command input
commands = st.text_area(
"Enter bash commands (one per line):",
height=400,
placeholder="""Example commands:
echo "Hello World"
ls -la
pwd
date
python --version""",
help="Enter your bash commands here. Each line will be executed as a separate command."
)
# Run button
run_button = st.button("🚀 Run Commands", type="primary", use_container_width=True)
with col2:
st.subheader("💻 Terminal Output")
# Create a container for terminal output
terminal_container = st.container()
# Style for terminal-like appearance
terminal_style = """
<style>
.terminal-output {
background-color: #1e1e1e;
color: #00ff00;
font-family: 'Courier New', monospace;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
white-space: pre-wrap;
word-wrap: break-word;
min-height: 400px;
max-height: 600px;
overflow-y: auto;
}
.command-line {
color: #00ffff;
font-weight: bold;
}
.error-line {
color: #ff6b6b;
}
.success-line {
color: #51cf66;
}
.timestamp {
color: #868e96;
font-size: 0.9em;
}
</style>
"""
st.markdown(terminal_style, unsafe_allow_html=True)
def run_bash_command(command):
"""Execute a bash command and return the output and error"""
try:
# Run the command with shell=True to allow complex bash commands
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=30 # 30 second timeout for commands
)
return {
'command': command,
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
except subprocess.TimeoutExpired:
return {
'command': command,
'stdout': '',
'stderr': 'Command timed out after 30 seconds',
'returncode': -1,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
except Exception as e:
return {
'command': command,
'stdout': '',
'stderr': f'Error executing command: {str(e)}',
'returncode': -1,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
# Execute commands when button is clicked
if run_button and commands:
# Split commands by newline and filter empty lines
command_list = [cmd.strip() for cmd in commands.split('\n') if cmd.strip()]
if command_list:
# Clear previous results
st.session_state.command_history = []
# Create progress bar
progress_bar = st.progress(0)
status_text = st.empty()
# Execute each command
for i, cmd in enumerate(command_list):
status_text.text(f"Running command {i+1}/{len(command_list)}: {cmd[:50]}...")
result = run_bash_command(cmd)
st.session_state.command_history.append(result)
progress_bar.progress((i + 1) / len(command_list))
# Clear progress indicators
progress_bar.empty()
status_text.empty()
# Show success message
st.success(f"✅ Successfully executed {len(command_list)} command(s)")
# Display terminal output
with terminal_container:
if st.session_state.command_history:
terminal_output = ""
for result in st.session_state.command_history:
# Add timestamp
terminal_output += f'<span class="timestamp">[{result["timestamp"]}]</span>\n'
# Add command
terminal_output += f'<span class="command-line">$ {result["command"]}</span>\n'
# Add stdout if present
if result['stdout']:
terminal_output += result['stdout']
if not result['stdout'].endswith('\n'):
terminal_output += '\n'
# Add stderr if present
if result['stderr']:
terminal_output += f'<span class="error-line">{result["stderr"]}</span>\n'
# Add return code if non-zero
if result['returncode'] != 0:
terminal_output += f'<span class="error-line">Exit code: {result["returncode"]}</span>\n'
terminal_output += '\n'
# Display in terminal-like div
st.markdown(
f'<div class="terminal-output">{terminal_output}</div>',
unsafe_allow_html=True
)
else:
# Show empty terminal
st.markdown(
'<div class="terminal-output">Terminal output will appear here after running commands...</div>',
unsafe_allow_html=True
)
# Sidebar with additional features
with st.sidebar:
st.header("⚙️ Settings & Info")
# Clear history button
if st.button("🗑️ Clear Terminal", use_container_width=True):
st.session_state.command_history = []
st.rerun()
# Show command history count
if st.session_state.command_history:
st.info(f"📊 Commands executed: {len(st.session_state.command_history)}")
# Safety warning
st.warning("""
⚠️ **Safety Notice**
This app executes commands directly on your system.
Please be careful with:
- Commands that modify files
- Commands with sudo/admin privileges
- Commands that could affect system settings
""")
# Examples section
st.subheader("📚 Example Commands")
st.code("""# System info
uname -a
whoami
pwd
# File operations
ls -la
cat filename.txt
find . -name "*.py"
# Network
ping -c 4 google.com
curl https://api.github.com
# Python
python --version
pip list""", language="bash")
# Footer
st.markdown("---")
st.markdown("Made with ❤️ using Streamlit | Use responsibly!")