Question:
How can you securely execute a dynamic shell command in Python using
---
Answer:
The above code demonstrates secure execution of dynamic shell commands by avoiding
#Python #OSModule #Security #ShellInjection #Subprocess #Sandboxing #SecureCode #AdvancedPython
By: @DataScienceQ 🚀
How can you securely execute a dynamic shell command in Python using
os module while preventing shell injection, handling environment variables, and ensuring the process is isolated with limited privileges? Provide a detailed example demonstrating all these aspects.---
import os
import subprocess
import tempfile
import shutil
import sys
from pathlib import Path
# Secure execution of dynamic shell commands
def secure_execute(cmd: str, cwd: str = None, env: dict = None):
# Validate input to prevent shell injection
if not isinstance(cmd, str) or not cmd.strip():
raise ValueError("Command must be a non-empty string.")
# Split command into safe components (avoid shell=True)
try:
args = cmd.split()
if not args:
raise ValueError("Invalid command format.")
# Sanitize arguments to avoid path traversal or injection
for arg in args:
if any(c in arg for c in [';', '&', '|', '>', '<', '`', '$']):
raise ValueError(f"Malicious character detected in command: {arg}")
# Use temporary directory for isolation
temp_dir = tempfile.mkdtemp(prefix="secure_exec_")
try:
# Set minimal environment
safe_env = {
'PATH': '/usr/bin:/bin',
'HOME': temp_dir,
'USER': 'sandbox_user',
}
if env:
safe_env.update(env)
# Run command with restricted privileges
result = subprocess.run(
args,
cwd=cwd,
env=safe_env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=30,
preexec_fn=os.setuid(1000), # Drop to unprivileged user
universal_newlines=True,
check=False
)
return {
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode,
'success': result.returncode == 0
}
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
except Exception as e:
return {'error': str(e)}
# Example usage
if __name__ == "__main__":
# Simulate a dynamic command from user input
user_input = "ls -la /tmp"
result = secure_execute(user_input, cwd="/")
print(result)
Answer:
The above code demonstrates secure execution of dynamic shell commands by avoiding
shell=True, splitting the command safely, validating input to prevent injection, isolating execution via a temporary directory, dropping privileges using os.setuid(), and restricting environment variables. This approach prevents common vulnerabilities like shell injection and privilege escalation.#Python #OSModule #Security #ShellInjection #Subprocess #Sandboxing #SecureCode #AdvancedPython
By: @DataScienceQ 🚀
❤3