这是我的第一篇博文,在此纪念一下。
本人在工作中经常需要用python处理数据和绘图,Anaconda自带的图形界面编辑器有spyder和jupyter notebook,在本地机器上我更习惯使用spyder,但是最近使用远程服务器的次数越来越多了,而spyger连接远程服务器的功能并不是很好用,因此转战jupyter,在此记录一下jupyter notebook访问远程服务器的配置过程。
1. 登录到远程服务器
打开一个bash窗口并登录远程服务器
$ssh -p port1 user@remoteaddress
2. 生成配置文件
user:localhost$jupyter notebook --generate-config
3. 在ipython中创建登录密码
远程打开notebook网页后会弹出对话框要求输入该密码
user:localhost$ipython
In [1]: from notebook.auth import passwd
In [2]: passwd()
Enter password:
Verify password:
Out[2]: 'argon2:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
In [3]: exit()
保存好生成的密钥
4. 修改配置文件
user:localhost$vi ~/.jupyter/jupyter_notebook_config.py
按i进入编辑模式,修改如下内容:
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.open_browser = False #不打开网页
c.NotebookApp.password = 'argon2:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #刚才生成的密钥
c.NotebookApp.port = port2 #自定义一个5位数以内的端口,如12345
按ESC退出编辑模式并输入
wq!
退出vim编辑器。
5. 启动notebook
user:localhost$jupyter notebook
启动后不要关闭该窗口,保持jupyter处于运行状态。
6. 和本地电脑建立ssh通道
在本地电脑上打开一个新的bash窗口,输入如下命令与远程服务器建立ssh通道
$ssh -fNL 8888:localhost:port2 -p port1 user@remoteaddress
此命令的意思是在port1 user@remoteaddress这台服务器上将第4步设置的port2端口映射到本地localhost的8888端口。
此时打开浏览器输入网址localhost:8888就会打开远程服务器上的jupyter notebook。
注:启动jupyter notebook后打开浏览器的默认都是8888端口,如果此端口被占用的话它会默认往上加1,例如此时在本地再打开一个jupyter notebook之后,端口会是8889。同样的如果在建立远程ssh通道前已经在本地打开了一个jupyter notebook,那么8888端口也会被占用,因此第6步的8888端口也需要改成8889等其它端口。
7. 使用小技巧
上述6步测试通过后为了下次使用方便可以结束第5步中的notebook,在远程机器上运行命令转为后台运行:
user:localhost$nohup jupyter notebook &
同时本地机器在~/.bashrc中加入一行命令:
$alias jups='ssh -fNL 8888:localhost:port2 -p port1 user@remoteaddress'
此后每次想打开远程服务器上的jupyter notebook都可以直接在本地机器上输入命令
$jups
然后打开网址localhost:8888即可。