Skip to content

Instantly share code, notes, and snippets.

@lacava
Created March 11, 2022 03:28
Show Gist options
  • Save lacava/c4566b2d11444a1a87e44a8cec7e25e9 to your computer and use it in GitHub Desktop.
Save lacava/c4566b2d11444a1a87e44a8cec7e25e9 to your computer and use it in GitHub Desktop.
list notebooks on a remote machine
"""
William La Cava 2020
license: GPL v3
this script connects to a server via ssh, looks for running
jupyter notebooks, and lists them.
note: for this to work, ssh needs to find the jupyter command on your
remote machine. if you have jupyter in /home/you/anaconda3/bin/,
for example, you can symlink it to /usr/local/bin to achive this:
ln -s /home/you/anaconda3/bin/jupyter /usr/local/bin/
in addition, you should have jupyter configured on the host to listen on the
network (0.0.0.0) instead of 'localhost'. That way you can connect without
port forwarding. Read more:
https://lerner.co.il/2017/02/01/five-minute-guide-setting-jupyter-notebook-server/
"""
import sys
import subprocess
import os
host = sys.argv[1]
response = subprocess.Popen(["ssh",host,"jupyter notebook list"],
stdout=subprocess.PIPE)
urls = []
# get hostname from ~/.ssh/config if it exists
record_hostname = False
if ('HOME' in os.environ.keys()
and os.path.exists(os.environ['HOME']+'/.ssh/config')
):
with open(os.environ['HOME']+'/.ssh/config','r') as f:
for line in f.readlines():
if line.startswith('Host') and host in line:
record_hostname = True
elif 'HostName' in line and record_hostname:
hostname = line.split('HostName')[-1].strip()
break
else:
hostname = host
# replace '0.0.0.0' with hostname
for url in response.stdout.readlines():
url = url.decode().replace('0.0.0.0',hostname)
urls.append(url)
print(f'listing notebooks on {hostname}')
for url in urls:
print(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment