Security
Command Injection in Python: How to Fix It
Command injection occurs when user input is passed to a system shell command. Python's os.system() with string concatenation is a common attack vector.
❌ Vulnerable Code
import os
filename = request.form['filename']
os.system(f'cat /uploads/{filename}')✅ Secure Fix
import subprocess
filename = request.form['filename']
if not filename.replace('-','').replace('_','').isalnum():
raise ValueError('Invalid filename')
result = subprocess.run(['cat', f'/uploads/{filename}'], capture_output=True, text=True)💡
Pro tip: Never use shell=True with user input. Pass arguments as a list to subprocess.run() to bypass shell interpretation entirely.
Paste this code into LearnCodeGuide
Detect Python vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Python Code →