forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell_handler.py
More file actions
41 lines (34 loc) · 1.38 KB
/
Copy pathshell_handler.py
File metadata and controls
41 lines (34 loc) · 1.38 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
import subprocess
import platform
import shlex
import logging
# Define allowed commands (example)
ALLOWED_COMMANDS = {'ls', 'pwd', 'whoami', 'date', 'echo'}
def execute_command(command: str) -> str:
# Log all command attempts
logging.info(f"Command execution attempt: {command}")
# Basic input validation
if not command or len(command.strip()) == 0:
return "Error: Empty command"
# Parse command safely
try:
cmd_parts = shlex.split(command)
if not cmd_parts:
return "Error: Invalid command format"
base_command = cmd_parts[0]
if base_command not in ALLOWED_COMMANDS:
return f"Error: Command '{base_command}' not allowed"
except ValueError as e:
return f"Error: Invalid command syntax: {e}"
try:
if platform.system() == "Windows":
result = subprocess.run(cmd_parts, capture_output=True, text=True, timeout=30)
else:
result = subprocess.run(cmd_parts, capture_output=True, text=True, timeout=30)
# Separate stdout and stderr for better security
if result.returncode != 0:
return f"Command failed (exit code {result.returncode}): {result.stderr.strip()}"
return result.stdout.strip()
except Exception as e:
logging.error(f"Command execution error: {e}")
return f"Error executing command: {e}"