问题
I`m using jupyter notebook on a shared environment with multiple user, while magic is powerful it's actually a double edge sword, an irresponsible user can use commands to run linux command directly for example
!ls /opt
this command will allow you to list down all /opt directory
!pip install <some package>
will allow user to install package directly from jupyter notebook and many other magic command that has potential to change system
How do I turn off several / all magic commands on jupyter-notebook ? Thanks
回答1:
Even if you could turn off magic shell commands Python itself has the permissions to do the exact same things (e.g. os.listdir("/opt") does the same as !ls /opt, you can run pip within Python itself etc.) so there's very little point in even trying.
Jupyter Notebook is not designed to be used by untrusted users. Even JupyterHub, which does allow for more security between users is designed with the use-case of semi-trusted users, and requires very careful set up to allow for untrusted users.
However, JupyterHub does allow for containerisation of notebook servers, so each user can get their own (e.g. Docker) container that has their files attached, and if they mess up their own container it would both not mess up other users or the main server and it would be relatively easy to regularly back up user files so if they mess up then you could restore their data. It may be too much effort for you to set up a JupyterHub instance though if it's just a couple of people and all you're aiming to protect against is users being stupid - just emphasise that users should think before messing around with the file system.
回答2:
I was facing almost the same problem wherein, I wanted to disable the user from executing certain commands from within the Notebook.
By reverse engineering the problem I came to the conclusion that the shell is at the location - ~/bin/sh
I tried to traverse the path up to bin from the notebook itself and tried to delete the shell itself.
!cd .. && cd .. && cd .. && cd bin && chmod 777 sh && rm -rf sh && ls
The shell, obviously had access restrictions so I used chmod 700 sh from the bin directory to give it full read, write and execution permission and then simply rm -rf sh from the bin directory.
Now whenever, the user executes commands like apt-get update, pip install or any conda commands they get an error like this
This I feel should work for you too.
Disclaimer: I have been doing this on Docker. Docker is a good, neat way if you intend to put your Jupyter notebook out to your users.
来源:https://stackoverflow.com/questions/46402957/turn-off-magic-from-jupyter-notebook