远程服务器上运行Jupyter笔记本的脚本

4
我有一台运行jupyter笔记本的服务器(Ubuntu Server 16.04),以及一台使用Google Chrome可视化这些笔记本的本地机器(Mac)。为了做到这一点,我需要执行以下操作:
  1. 在服务器上运行jupyter笔记本:
  2. jupyter notebook --no-browser --port=${remotePort}

  3. 在本地机器上指定一个SSH隧道:
  4. ssh -f ${username}@${serverIP} -L ${localPort}:localhost:${remotePort}

为了自动化这个过程,我创建了一个名为jupyter.sh的脚本(如下所述),以便只需在我的本地机器上运行:
bash jupyter.sh -u myUserNameInServer

这个工具运行得非常顺畅,可以执行前面两个步骤,并自动在我的浏览器中打开jupyter页面。不过,我想知道是否有更好的方法来完成这个任务。非常感谢您的建议。

先感谢您了。

#######################################################################
## 1. SET VARIABLES TO STABLISH THE SSH CONNECTION
# Get username from command line: bash jupyter.sh -u username
while [[ $# -gt 1 ]]
do
key="$1"
case $key in
    -u|--username)
    username="$2"
    shift # past argument
    ;;
esac
shift # past argument or value
done
# Specificy other variables to stablish the ssh connection
localPort=8890
browser="Google Chrome"
serverIP=the_IP_of_the_server
#######################################################################
# 2. RUN JUPYTER IN REMOTE SERVER
out=$(ssh -T ${username}@${serverIP} <<HERE
    # Only run jupyter if it isn't already running
    if [ \$(ps -u ${username} | grep jupyter | wc -l) -eq 0 ]
    then
        # Create a folder called jupyter, and move into it
        if [ ! -d jupyter ]; then mkdir jupyter; fi
        cd jupyter
        # Create a script to run jupyter
        echo "jupyter notebook --no-browser --NotebookApp.token=${username}" > jupyter.sh 
        # Run jupyter in the background
        screen -S jupyter -d -m bash jupyter.sh
    fi
    # Output the remote port number. If there is more than 1, get the first one
    jupyter notebook list | grep localhost | awk '{split(\$0,a,"localhost:");split(a[2],b,"/"); print b[1]}' | head -n1
HERE
)

#######################################################################
# 3. SET SSH TUNNEL
# Pass the remote port to a variable in the local machine
remotePort=$(echo $out | awk '{print $NF}') 
# Start listening in local port 8890 if that port isn't already in use
# num equal 1 if port number is already in use, 0 otherwise
num=$(netstat -lnt | awk 'BEGIN{x=0} ($6 == "LISTEN" && $4 ~ "8890$"){x=1}END{print x}')
if [ $num -eq 0 ]
then
    ssh -f ${username}@${serverIP} -L ${localPort}:localhost:${remotePort} -N
fi
#
# Open jupyter in browser
open -a "${browser}" http://localhost:${localPort}/tree?token=${username} &
1个回答

1

您可以使用“jupyter配置文件”,但默认情况下未激活,因此需要首先执行此命令(在您的服务器上):

jupyter notebook --generate-config

在位于“/.jupyter”文件夹中生成的“jupyter_notebook_config.py”文件中:取消注释该行并更改其值。这样,您就可以调整配置,例如密码而不是令牌、默认目录、端口等。按照您想要的方式进行操作,这可能是在脚本中执行某些“jupyter config”的适当方式,然后保留其他所有内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接