Preventing Python code from importing certain modules? Preventing Python code from importing certain modules? python python

Preventing Python code from importing certain modules?


If you put None in sys.modules for a module name, in won't be importable...

>>> import sys>>> import os>>> del os>>> sys.modules['os']=None>>> import osTraceback (most recent call last):  File "<stdin>", line 1, in <module>ImportError: No module named os>>>


Have you checked the python.org article on SandboxedPython, and the linked article?

Both of those pages have links to other resources.

Specifically, PyPi's RestrictedPython lets you define exactly what is available, and has a few 'safe' defaults to choose from.


8 years, yeesh, and nobody has figured this one out? :/

You can override the import statement or aka the __import__ function.

This is just a tested scribble-code because I couldn't find any legit reference:

import importlibdef secure_importer(name, globals=None, locals=None, fromlist=(), level=0):    if name != 'C': print(name, fromlist, level)    # not exactly a good verification layer    frommodule = globals['__name__'] if globals else None    if name == 'B' and frommodule != 'C':        raise ImportError("module '%s' is restricted."%name)    return importlib.__import__(name, globals, locals, fromlist, level)__builtins__.__dict__['__import__'] = secure_importerimport C

and here's the tests for that code:

Python 3.4.3 |Anaconda 2.3.0 (32-bit)| (default, Mar  6 2015, 12:08:17) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> B ('f',) 0imported secure module>>> from B import fB ('f',) 0linecache None 0encodings.utf_8 ['*'] 0Traceback (most recent call last):  File "<pyshell#0>", line 1, in <module>    from B import f  File "\home\tcll\Projects\python\test\restricted imports\main.py", line 11, in secure_importer    raise ImportError("module '%s' is restricted."%name)ImportError: module 'B' is restricted.>>> import C>>> 

Please do not comment about me using Python34, I have my reasons, and it's my primary interpreter on Linux specifically for testing things (like the above code) for my primary project.