Alan Macdonald
Alan Macdonald

Reputation: 1900

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

Upvotes: 9

Views: 606

Answers (1)

Krumelur
Krumelur

Reputation: 32497

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.

Upvotes: 3

Related Questions