Running a Jupyter Notebook remotely in single line

In order to run a Jupyter Notebook on a remote server (here: SERVER), one usually first opens a shell, logs in on the remote server, starts the jupyter notebook server. Then usually you open a new shell, and forward a local port using ssh. And finally you open the notebook webpage in your browser (here: Firefox).

Now as I don’t always want to go through all the hassle of setting this up, I tried to figure out how one can do it in one line (actually two commands), in order to bind this to a single alias.  

And here it is:

bash -c "sleep 3"; firefox localhost:8888" &
ssh -L 8888:localhost:8888 USER@SERVER -t 'bash -ic "
cd /your/notebook/directory; 
jupyter notebook --ip=127.0.0.1 --port=8888 --no-browser"'

yep, that’s a lot of stuff going on, so lets look into it bit by bit (make sure if you copy/paste this, you remove the line-breaks 😉 ).

One of the problems is, that if you send the ssh session with the jupyter server running to the background, you loose the oportunity to close the jupyter server bei sending CTRL+C. So in order to avoid this, this needs to be executed last and not sent to the background. Unfortunately, we can only open the browser after the jupyter notebook is running, ending up with a hen and egg problem.

To circumvent this, we first start a shell, which starts the browser after 3 seconds (adjust this as needed, depending on your remote connection):

bash -c "sleep 3"; firefox localhost:8888"&

This runs a series of bash commands in the background (‘bash -c “…” &‘) – in our case we wait 3 seconds (‘sleep 3‘) and after this waiting period (in which the jupyter server should have started up), we start the browser (here ‘firefox‘) opening the notebook webpage on the selected port (i.e. ‘localhost:8888‘).

Now we only need to ssh to the server, forward the port and start the jupyter notebook server:

ssh -L 8888:localhost:8888 USER@SERVER -t 'bash -ic
"cd /your/notebook/directory;
jupyter notebook --ip=127.0.0.1 --port=8888 --no-browser"'

Meanwhile we open the ssh tunnel forwarding the local port (-L 8888:localhost:8888) to the remote server (USER@SERVER).

In my case it was important to run the remote session interactively, such as also the Anaconda configuration gets loaded with the remote servers .bashrc. Therefore, we execute a set of remote bash commands in interactive mode (-t ‘bash -ic”…” ‘). Here, I first change the directory to my notebooks directory (‘cd /your/notebook/directory‘), and finally I start the Jupyter Notebook server (jupyter notebook –ip=127.0.0.1 –port=8888 –no-browser). Note that you dont’t want to start the browser on the remote server (–no-browser) as we start it locally, in order not to cause too much trafic, or simply because no browser is installed on your remote server.