sai
sai

Reputation: 97

restrict importing certain modules in python

I am setting this sys.modules['os']=None for restricting OS modules in my python notebook. But I want to restrict it by default, is there any file in /bin where I can add this line. If not, is it possible in RestrictedPython?

Upvotes: 0

Views: 861

Answers (2)

hello world
hello world

Reputation: 624

First, there is no true sandboxing in python (you also can try PyPy, they claim that this is achievable all the way down to syscalls via rather nontrivial hooking inside their VM). But what you can try right now is runpy module from stdlib. It provides a way to run your module inside a restricted environment (yet not a sandbox) via providing this environment explicitly as a dict. Since import statement runs __import__ function underkeens, this function can be overloaded to not accept certain module names. Though I am not sure how to force Jupiter (or whatever you are using) to run in discussed mode.

Upvotes: 1

Stavros Avramidis
Stavros Avramidis

Reputation: 865

I don't think you can do that, but you could create a virualenv and delete those modules there

Upvotes: 1

Related Questions