Advertisement
Guest User

safe exec

a guest
Jun 30th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. import ast
  2.  
  3. CODE_SAFE = 0
  4. ERROR_IMPORT = 1
  5. ERROR_CLASS = 2
  6. ERROR_GLOBAL = 3
  7. ERROR_YIELD = 4
  8.  
  9. obj_banned = {
  10.     ast.Import: 1,
  11.     ast.ImportFrom: 1,
  12.     ast.ClassDef: 2,
  13.     ast.Global: 3,
  14.     ast.Yield: 4,
  15.     ast.YieldFrom: 5
  16. }
  17.  
  18.  
  19. def _is_safe(node):
  20.     if type(node) in obj_banned:
  21.         return obj_banned[type(node)]
  22.     return 0
  23.  
  24.  
  25. def check_safe(code):
  26.     source = ast.parse(code)
  27.     next = [source]
  28.     while len(next) > 0:
  29.         new_next = []
  30.         for obj in next:
  31.             result = _is_safe(obj)
  32.             if result > 0:
  33.                 return result
  34.             new_next += ast.iter_child_nodes(obj)
  35.         next = new_next
  36.     return 0
  37.  
  38.  
  39. def run_exec(code):
  40.     local_space = {"message": None, "spam": None}
  41.     exec(code, {}, local_space)
  42.     return local_space
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement