Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

Why is `shell=True` dangerous, and when is it acceptable?

IntermediateConceptOS, filesystem, subprocess & CLIs
Answer

With shell=True, the string is passed to /bin/sh -c, so any shell metacharacters in interpolated input execute. subprocess.run(f"git checkout {branch}", shell=True) with branch = "main; rm -rf ~" is command injection.

Acceptable only with fully constant strings where you genuinely need shell features (pipes, globbing) and no user input. Even then it is usually better to do the pipe in Python or quote with shlex.quote(). Bandit flags this as B602.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs