Run dynamic generated Python code safely

We've developed this to be able to run trusted methods as batch operations that were saved into database to be performed later on. The code is easy to understand reading its tests:

Tests: Check out this file

Code:

  1.  
  2. import os
  3. import inspect
  4. import inspect
  5.  
  6. class PythonInvoker():
  7. def __init__(self, targetBaseClass=None):
  8. self.targetBaseClass = targetBaseClass
  9.  
  10. def evalArgumentsIfNotStrings(self, param):
  11. if len(param) > 0:
  12. param = param.strip()
  13. if param[0] == "\"" or param[0] == "'":
  14. return param
  15. else:
  16. try:
  17. return eval(param,{"__builtins__":None},{})
  18. except NameError:
  19. raise ApplicationException("Security exception: arguments can only be variables. This argument is -> " + param)
  20. else:
  21. return param
  22.  
  23. def secureDynamicInvoke(self, classInstance, methodName, arguments):
  24. if isinstance(classInstance, self.targetBaseClass):
  25. return self.dynamicInvoke(classInstance, methodName, arguments)
  26. else:
  27. raise ApplicationException(str(classInstance) + " does not extends " + str(self.targetBaseClass))
  28.  
  29. def dynamicInvoke(self, classInstance, methodName, arguments):
  30. if arguments == None:
  31. arguments = ""
  32. try:
  33. method = getattr(classInstance, methodName)
  34. except AttributeError:
  35. raise ApplicationException("Method does not belong in class!: " + str(classInstance) + "-" + str(methodName))
  36. retInfo = None
  37. try:
  38. if re.search(",", arguments):
  39. args = arguments.split(",")
  40. args = map(self.evalArgumentsIfNotStrings, args)
  41. retInfo= method(*args)
  42. else:
  43. retInfo= method()
  44. except TypeError, e:
  45. raise ApplicationException(str(classInstance) + "." + str(methodName) + " - " + e.message)
  46. return retInfo
  47.  
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  • http://www.belweder.velvet.beskidy.pl/ Dula

    Partner, this amazing site is without a doubt fabolous, i like it so much