Skip to main content

27. The Dangers of Eval and Exec

eval() and exec() can execute arbitrary code and are common sources of remote code execution (RCE) vulnerabilities.

Insecure Example​

data = input("Enter a command: ")
eval(data) # User can run any Python code!

Secure Example​

allowed_ops = {"add": lambda x, y: x + y, "mul": lambda x, y: x * y}
cmd = input("Enter operation (add/mul): ")
if cmd not in allowed_ops:
raise ValueError("Invalid command")
print(allowed_ops[cmd](2, 3))

✅ Lesson: Never execute user input. Replace dynamic execution with safe lookup logic.