'Set Jupyter Notebook password in bash script through environment variable

I have come across the following code in a bash script for automatic deployment and setup of Jupyter Notebook. There are issues when the password contains a #, as the rest of the line is treated as a comment (and probably raises an exception in Python due to lack of closing bracket):

# Set up Jupyter Notebook with the same password
su - $USERNAME -c "$SHELL +x" << EOF
  mkdir -p ~/.jupyter
  python3 -c "from notebook.auth.security import set_password; set_password(password=\"$PASSWORD\")"
EOF

Obviously this is not an ideal way to set a password due to the above issues.

I am wondering what best practice would be in this situation? Using triple-quotes instead of single enclosing quotes might be better, but still runs into issues if the supplied password has triple quotes. How is this situation normally tackled?



Solution 1:[1]

Instead of passing the password through a bash here-document, just use python to read it from the environment:

# Set up Jupyter Notebook with the same password
su - $USERNAME -c "$SHELL +x" << EOF
  mkdir -p ~/.jupyter
  python3 -c "from notebook.auth.security import set_password; import os; set_password(password=os.environ['PASSWORD'])"
EOF

Solution 2:[2]

You can pass Jupyter command line optionsenter link description here to notebook like its done for docker. The method is save as it will use ths sha. the start-notebook.sh script looks like this:source.

#!/bin/bash
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

set -e

wrapper=""
if [[ "${RESTARTABLE}" == "yes" ]]; then
  wrapper="run-one-constantly"
fi

if [[ ! -z "${JUPYTERHUB_API_TOKEN}" ]]; then
  # launched by JupyterHub, use single-user entrypoint
  exec /usr/local/bin/start-singleuser.sh "$@"
elif [[ ! -z "${JUPYTER_ENABLE_LAB}" ]]; then
  . /usr/local/bin/start.sh $wrapper jupyter lab "$@"
else
  . /usr/local/bin/start.sh $wrapper jupyter notebook "$@"
fi

For example, to secure the Notebook server with a custom password hashed using IPython.lib.passwd() instead of the default token, you can run the following to test via docker:

#generate a password
from IPython.lib.security import passwd
passwd(passphrase=None, algorithm='sha1')


# run test in docker
docker run -d -p 8888:8888 jupyter/base-notebook start-notebook.sh --notebookApp.password='sha1:31246c00022b:cd4a5e1eac6b621284331642a27b621948d80a92'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ian Hinder
Solution 2