Subprocess Security

Domain: Security

🎯 Motivation

Running external commands from Python is powerful but risky. Using shell=True or interpolating input opens the door to command injection, so prefer argument lists and avoid the shell.

πŸ“‹ Concrete Example

subprocess.run(["ls", user_dir], shell=False) is safe. subprocess.run(f"ls {user_dir}", shell=True) is not β€” a user_dir like .; rm -rf / runs two commands. Always pass a list.

πŸ”— Analogy

Handing a recipe to a cook step by step is safe. If you hand them a free-form note, they might interpret β€œadd salt; also leave the stove on” as two instructions β€” one of them dangerous.