Skip to content

Instantly share code, notes, and snippets.

@cldotdev
Last active December 17, 2015 12:58
Show Gist options
  • Select an option

  • Save cldotdev/5613279 to your computer and use it in GitHub Desktop.

Select an option

Save cldotdev/5613279 to your computer and use it in GitHub Desktop.
Preventing Python code from importing certain modules
#!/usr/bin/env python
# http://marlonyao.iteye.com/blog/905313
# Usage: $ python sandbox.py <untrusted.py>
_builtins = dict(__builtins__.__dict__)
def _hook_import(name, *args, **kwargs):
restricted_modules = [
'os',
'subprocess',
'ctypes',
'shutil',
]
if name in restricted_modules: # now allow to import os
raise ImportError('Cannot import %s' % (name))
# otherwise, use default __import__
return __import__(name, *args, **kwargs)
# Replace __import__ with our hook implementation
_builtins['__import__'] = _hook_import
# Remove built-in function: open()
_builtins.pop('open')
if __name__ == '__main__':
import sys
_restricted_globals = {
'__builtins__': _builtins,
}
with open(sys.argv[1], 'r') as fi:
source = ''.join(fi.readlines())
code = compile(source, '<string>', 'exec')
try:
exec(code) in _restricted_globals
except ImportError as msg:
# Do something for ImportError exception.
print(msg)
except NameError as msg:
# Do something for NameError exception.
print(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment