Total 4 steps for connect & exit Jupyter Notebook with a SSH server:
-
SSH to the Server. Run:
jupyter notebook --no-browser --port=8888
-
Open another terminal window on your local machine, input:
ssh -NL localhost:1234:localhost:8888 <remoteuser@server>
It listens port 1234 (you can change this number) on local machine, which is forwarded from port 8888 of the remote machine.
The
<remoteuser@server>
doesn't need to be a format with "@" symbol in it. It can be specified inc:\users\<username>\.ssh\config
, I think you must have learned it if you are a SSH user. -
Open browser on your local machine, input
localhost:1234
, and copy the token from the step 1. If you don't want a token, set a password instead usingjupter notebook password
. -
After things are done,
CTRL + C
to terminate the remote SSH Jupyter server. To stop local machine's port listening on 1234, usenetstat
to find the PID of process on the port 1234:# If local is Linux sudo netstat -lpn | grep :1234 kill <PID number>
For Windows, things are similar:
# If local is Windows, close the terminal directly and reopen one with Administrator: ## If using CMD netstat -ano | findstr :1234 ## If using Powershell Get-Process -Id (Get-NetTCPConnection -LocalPort 1234).OwningProcess
then kill it with
taskkill /PID <PID number> /F
.
As an alternative, you can write the first step's command into ~/.bash_aliases
file if the remote machine is running on Linux:
alias jupyterremote='jupyter notebook --no-browser --port=8888'
Then you can input jupterremote
in terminal instead this long command. Here, ~/.bash_aliases
is the file I'm using due to following setting in my ~/.bashrc
:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
You might have ~/.bash_alias
or something similar. If not, you can create a new one.
This part takes more effort to achieve. But we can still set an alias for Windows. In your PowerShell's $profile
(see Set-Alias-on-Windows-PowerShell.md
below for details), enter:
function JupyterListening {
param(
$remote = "sshserver",
$localport = 1234,
$remoteport = 8888
)
ssh -NL localhost:$localport:localhost:$remoteport $remote
}
New-Alias jupyterlisten JupyterListening
# Find PID of precess on given port
function FindPortPID {
param($port = 1234)
Get-Process -Id (Get-NetTCPConnection -LocalPort $port).OwningProcess
}
New-Alias findport FindPortPID
Then you are free to go. In the step 2 of the main process, you only need jupyterlisten
to listen the port. If you are connecting to a different remote or using different ports, use its full-formatted command:
jupyterlisten -remote <servername> -localport 1234 -remoteport 8888
Under local Windows & server Linux environment:
PS > ssh sshserver
user@sshserver:~$ jupyterremote
Open another powershell:
jupyterlisten
Open browser, enter localhost:1234
(or you can bookmark it). Then enjoy Jupyter running on remote.