Saira20 commited on
Commit
181b113
·
1 Parent(s): 9b62595

Prevent dangerous commands as suggested by the LLM

Browse files
Files changed (1) hide show
  1. app.py +120 -8
app.py CHANGED
@@ -1,18 +1,130 @@
1
  import gradio as gr
 
 
2
  import os
3
 
4
- async def run_command(command: str) -> str:
 
 
 
5
  """
6
- Run a command on shell.
 
 
 
 
7
  Returns:
8
- Output of the command.
9
  """
10
- return os.popen(command).read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- with gr.Blocks(title="Your wish is my command") as demo:
14
- gr.Interface(run_command, inputs=gr.Textbox(), outputs=gr.Code(), api_name="run_command")
15
 
16
  if __name__ == "__main__":
17
- print("Hello from llm-shell-executor!")
18
- demo.launch(mcp_server=True, show_error=True, theme=gr.themes.Glass())
 
 
 
 
 
 
1
  import gradio as gr
2
+ import subprocess
3
+ from typing import Tuple
4
  import os
5
 
6
+ # Security: Define allowed commands or use a whitelist approach
7
+ DANGEROUS_COMMANDS = ['rm -rf /', 'dd if=', 'mkfs', ':(){ :|:& };:']
8
+
9
+ async def run_command(command: str) -> Tuple[str, str]:
10
  """
11
+ Run a command on shell with improved security and error handling.
12
+
13
+ Args:
14
+ command: Shell command to execute
15
+
16
  Returns:
17
+ Tuple of (output, status_message)
18
  """
19
+ if not command or not command.strip():
20
+ return "", "❌ Error: Empty command provided"
21
+
22
+ # Basic security check for obviously dangerous commands
23
+ for dangerous in DANGEROUS_COMMANDS:
24
+ if dangerous in command:
25
+ return "", f"🚫 Security: Command blocked (contains: {dangerous})"
26
+
27
+ try:
28
+ # Use subprocess instead of os.popen for better control
29
+ result = subprocess.run(
30
+ command,
31
+ shell=True,
32
+ capture_output=True,
33
+ text=True,
34
+ timeout=30, # Prevent hanging commands
35
+ cwd=os.getcwd()
36
+ )
37
+
38
+ # Combine stdout and stderr
39
+ output = result.stdout
40
+ if result.stderr:
41
+ output += f"\n--- STDERR ---\n{result.stderr}"
42
+
43
+ if result.returncode == 0:
44
+ status = f"✅ Success (exit code: {result.returncode})"
45
+ else:
46
+ status = f"⚠️ Command exited with code: {result.returncode}"
47
+
48
+ return output or "(no output)", status
49
+
50
+ except subprocess.TimeoutExpired:
51
+ return "", "⏱️ Error: Command timed out (30s limit)"
52
+ except Exception as e:
53
+ return "", f"❌ Error: {str(e)}"
54
+
55
 
56
+ def create_interface():
57
+ """Create the Gradio interface with improved UI"""
58
+ with gr.Blocks(
59
+ title="Shell Command Executor",
60
+ ) as demo:
61
+ gr.Markdown("""
62
+ # 🖥️ Shell Command Executor
63
+ Execute shell commands safely with timeout protection and error handling.
64
+
65
+ **⚠️ Warning**: Use with caution. Some dangerous commands are blocked.
66
+ """)
67
+
68
+ with gr.Row():
69
+ with gr.Column(scale=2):
70
+ command_input = gr.Textbox(
71
+ label="Command",
72
+ placeholder="Enter your shell command (e.g., ls -la, pwd, echo 'hello')",
73
+ lines=2
74
+ )
75
+
76
+ with gr.Row():
77
+ run_btn = gr.Button("▶️ Run Command", variant="primary")
78
+ clear_btn = gr.Button("🗑️ Clear")
79
+
80
+ with gr.Column(scale=1):
81
+ status_output = gr.Textbox(
82
+ label="Status",
83
+ lines=2,
84
+ interactive=False
85
+ )
86
+
87
+ output_display = gr.Code(
88
+ label="Output",
89
+ language="shell",
90
+ lines=15
91
+ )
92
+
93
+ gr.Markdown("""
94
+ ### 📝 Example Commands
95
+ - `pwd` - Print working directory
96
+ - `ls -la` - List files with details
97
+ - `whoami` - Show current user
98
+ - `df -h` - Show disk usage
99
+ - `ps aux | head -n 10` - Show top 10 processes
100
+ """)
101
+
102
+ # Event handlers
103
+ run_btn.click(
104
+ fn=run_command,
105
+ inputs=command_input,
106
+ outputs=[output_display, status_output]
107
+ )
108
+
109
+ command_input.submit(
110
+ fn=run_command,
111
+ inputs=command_input,
112
+ outputs=[output_display, status_output]
113
+ )
114
+
115
+ clear_btn.click(
116
+ fn=lambda: ("", "", ""),
117
+ outputs=[command_input, output_display, status_output]
118
+ )
119
+
120
+ return demo
121
 
 
 
122
 
123
  if __name__ == "__main__":
124
+ print("🚀 Starting Shell Command Executor...")
125
+ print("⚠️ Security features enabled: timeout protection, basic command filtering")
126
+
127
+ demo = create_interface()
128
+ demo.launch(
129
+ mcp_server=True,
130
+ show_error=True)