Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing imports in Python

I have python embedded in an application as a scripting platform so the users can write python scripts. I am trying to prevent imports so they cannot cause damage in anyway and have to stick to the provided API.

I have come up with the following Python code:

__builtins__ .__import__= None 
reload = None

This seems to prevent imports and prevents reloading of modules. The prevention of reloading is required so they can't reload builtins giving them back a working import.

However I am not a Python expert. Is there anything else I am missing that the user can still do to import modules?

Thanks

like image 655
Alan Macdonald Avatar asked Dec 08 '11 09:12

Alan Macdonald


People also ask

How do you organize imports in Python?

Organize imports into groups: first standard library imports, then third-party imports, and finally local application or library imports. Order imports alphabetically within each group. Prefer absolute imports over relative imports. Avoid wildcard imports like from module import * .

What are the three types of import statement in Python?

There are generally three groups: standard library imports (Python's built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application)


1 Answers

What you probably want is to run Python in a sandbox. There are a number of ways of doing this, for example PyPy has sandboxing support.

You could also try sandboxing the Python process itself using external tools, but I suppose this is dependent on the operating system.

like image 66
Krumelur Avatar answered Nov 14 '22 06:11

Krumelur