Convenient method to connect to Jupyter notebooks on a private server over SSH


This function allows you to run a single command from your laptop that will start the Jupyter notebook server on a remote machine (unless it's already started), and then set up the necessary port forwarding over SSH. Once you run this command, you can navigate to localhost:8889 on your laptop and you can work with the notebooks on the remote server. The server will need the screen utility to be installed.

function rj() {
  # connects to remote jupyter notebook server 
  ssh USERNAME@SERVER_ADDRESS 'screen -dmS jupyter-notebook bash -c "path/to/jupyter notebook --no-browser --port=8892 --port-retries=0"'

  # kill any stale connections
  existing_process=`ps aux | grep -v grep | grep "fNL localhost" | awk '{print $2}'`
  if [[ ! -z "$existing_process" ]]; then 
    kill $existing_process 
  fi

  # connect to server and forward some ports
  ssh -fNL localhost:8889:localhost:8892 USERNAME@SERVER_ADDRESS
}

Tradeoffs and caveats: anyone else with SSH access to the server will be able to see your notebooks. Each user will also need their own, unique port.