一般而言,需要通过跳板机连接的远程服务器和跳板机本身处在同一个内网当中,本文主要介绍如何在外网访问带跳板机的目标服务器的Jupyter,即本地机->跳板机->服务器的二次转发访问下使用服务器的Jupyter在本地浏览器进行交互式编程。
- 使用xshell等远程连接工具,先建立本地机与跳板机之间的连接访问,再建立SSH隧道访问目标服务器的访问,此时一般需要使用本地机的某个端口侦听目标服务器的22端口。
- 通过第一步的配置,我们先实现了本地机对目标服务器的远程访问,接着进行jupyter的安装与配置。这里首先进入服务器命令行终端,通过以下命令生成服务器端的Jupyter配置文件:
pip install jupyter jupyter notebook --generate-config
此时会在root/.jupyter/目录下生成jupyter_notebook_config.py配置文件。接着在服务器root目录下通过vim进入并编辑该文件:
vim ./.jupyter/jupyter_notebook_config.py
修改如下:
c.NotebookApp.ip='*' c.NotebookApp.allow_remote_access = True c.NotebookApp.password = '你通过passwd生成的密文' c.NotebookApp.open_browser = False c.NotebookApp.port =8889
这里可以在vim命令模式下通过/+关键字的形式查找对应的部分,取消注释后修改。由于配置文件内所有内容已被预先注释,这里为了方便直接在文件的开头加入上述配置内容。
- 关于如何生成密文,这里先在终端命令行通过ipython进入python console交互模式,接着输入:
from notebook.auth import passwd
passwd()
注意在某些较老的版本中passwd()命令默认生成sha1开头的密文,参考之前的一些教程内容,此时应该需要输入u'sha1xxxxxx'作为完整的密文配置。我这里默认生成的是argon2开头的密文,这里直接复制输入'argon2xxxxxx'即可。
- 最后,对于我所在的环境与版本,按照上述内容配置可以成功打开Jupyter,但会出现如下warning
[W 2021-03-25 09:13:52.932 NotebookApp] 'ip' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-03-25 09:13:52.932 NotebookApp] 'allow_remote_access' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-03-25 09:13:52.932 NotebookApp] 'password' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-03-25 09:13:52.932 NotebookApp] 'password' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-03-25 09:13:52.933 NotebookApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
此时需要将配置文件中的NotebookApp全部替换为ServerApp即可,完整的配置文件如下所示:
c.ServerApp.ip='*'
c.ServerApp.allow_remote_access = True
c.ServerApp.password = 'argon2xxxxxxxxxx'
c.ServerApp.open_browser = False
c.ServerApp.port=8889 # 这里可以任意设置服务器未使用的端口
- 最后一步,在服务器命令行终端输入jupyter notebook或jupyter lab启动服务器端的jupyter后,需要使用xshell额外建立一个会话,同样地先连接到跳板机,然后建立隧道用本地机的空闲端口(如1111)侦听服务器端的8889端口,也即上面我们所配置的port,如下所示:
然后在本地机浏览器打开127.0.0.1:1111即可成功打开服务器端的jupyter。
此外,关于在jupyter上新增虚拟环境/kernel,比较简单,如下所示:
#先进入你所需要新增的环境yourenv
conda activate yourenv
#在该环境的命令行进行配置
conda install ipykernel # 安装新增kernel所需要的的包
ipython kernel install --user --name yourenv --display-name xxx # xxx是yourenv在jupyter的显示名字,非必要可以不加--display-name命令
配置完成后可以在jupyter notebook/lab上看到新增的kernel环境。
此外,第一次在本地机远程登录需要输入登录密码,此登录密码可以通过在服务器上设置
jupyter notebook password # 接下来连续输入两次即可成功设置登录密码