← Lesson
Code Interpreters
Joeven
Run
Reset
Python loads on first run
import ast import operator ALLOWED_OPS = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod, ast.Pow: operator.pow, ast.USub: operator.neg, } class SandboxError(ValueError): pass def safe_arith(expr): tree = ast.parse(expr, mode="eval") def ev(node): if isinstance(node, ast.Expression): return ev(node.body) if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): return float(node.value) if isinstance(node, ast.UnaryOp) and type(node.op) in ALLOWED_OPS: return ALLOWED_OPS[type(node.op)](ev(node.operand)) if isinstance(node, ast.BinOp) and type(node.op) in ALLOWED_OPS: return ALLOWED_OPS[type(node.op)](ev(node.left), ev(node.right)) raise SandboxError("forbidden node: " + type(node).__name__) return ev(tree) samples = [ "(3 + 4) * 10", "2 ** 8", "__import__('os').system('echo pwned')", "open('/etc/passwd').read()", ] for s in samples: try: print(s, "->", safe_arith(s)) except Exception as e: print(s, "->", type(e).__name__ + ":", e)
Run to execute this in your browser. Nothing is sent to a server.