Skip to main content

42. Command Injection (Intro)

Command injection happens when attacker-controlled input is passed to a shell or external program without proper escaping.

Insecure Example​

filename = input("Enter filename: ")
os.system("tar -czf archive.tar.gz " + filename) # Unsafe

Secure Example​

import subprocess
filename = input("Enter filename: ")
subprocess.run(["tar", "-czf", "archive.tar.gz", filename], check=True)

✅ Lesson: Avoid shell=True and never concatenate user input into shell commands.