Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
connect colaboratory by ssh
import random, string, urllib.request, json, getpass, time
#Generate root password
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
#Download ngrok
! wget -q -c -nc
! unzip -qq -n
#Setup sshd
! apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen vim > /dev/null
#Set root password
! echo root:$password | chpasswd
! mkdir -p /var/run/sshd
! echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
! echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config
! echo "LD_LIBRARY_PATH=/usr/lib64-nvidia" >> /root/.bashrc
! echo "PATH=/usr/local/cuda/bin:$PATH" >> /root/.bashrc
! echo "LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH" >> /root/.bashrc
! echo "export PATH" >> /root/.bashrc
! echo "export LD_LIBRARY_PATH" >> /root/.bashrc
#Run sshd
get_ipython().system_raw('/usr/sbin/sshd -D &')
#Ask token
print("Copy authtoken from")
authtoken = getpass.getpass()
#Create tunnel
get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')
#Wait for wake up sshd
#Get public address and print connect command
with urllib.request.urlopen('http://localhost:4040/api/tunnels') as response:
data = json.loads(
(host, port) = data['tunnels'][0]['public_url'][6:].split(':')
print(f'SSH command: ssh -p{port} root@{host}')
#Print root password
print(f'Root password: {password}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment