Skip to main content

35. Safe Subprocess and OS Interactions

Running shell commands from Python can be dangerous when input is not validated.
Avoid os.system() and use subprocess.run() with argument lists.

Insecure Example

import os
filename = input("Enter file to list: ")
os.system(f"ls {filename}") # Injection risk: filename='; rm -rf /'

Secure Example

import subprocess, shlex

filename = input("Enter file to list: ")
if not filename.isalnum():
raise ValueError("Invalid filename.")
subprocess.run(["ls", filename])

Lesson: Never pass user input directly to shell commands. Always use subprocess argument lists.