SSH to Google Colaboratory with

I love Google Colab! It is perfect for running Deep Learning experiments on a budget. I like how nonrestrictive it is and how you can run whatever you want inside the container you are given.

Sometimes I like to connect via SSH and use a proper editor to edit my python scripts, and while Jupyter-like environment is great for visualizing etc. sometimes you just want a shell. Luckily you can SSH into your Colab runtime.

Now, full disclaimer, I do not know if Google allows this explicitly or they just didn’t consider it. If I am asked to remove this guide I will immediately do so.

To get SSH access you need a bridge of some sort. There are already some tutorials using ngrok but that requires you to make an account there. What I came up with is much simpler.

Here are the steps:

  1. Open a new Colab notebook (you can name it ssh for future use)

  2. Set your runtime to Python 3 and GPU (optional)

  3. In a cell run the following code:

import random, string, getpass

password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
alias = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))
! echo root:$password | chpasswd

! apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen > /dev/null
! 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 "export LD_LIBRARY_PATH" >> /root/.bashrc
get_ipython().system_raw('/usr/sbin/sshd -D &')

print('sshpass -p {} ssh -o "StrictHostKeyChecking no" -J root@{}'.format(password, alias))
! ssh -o "StrictHostKeyChecking no" -R $alias:22:localhost:22

That’s it! The output will be a command that you can run locally to connect. Package sshpass is required if you want to skip the password prompt, but unnecessary otherwise.

Example output:

sshpass -p Xw11kuSeS3F4hBSFkYs2 ssh -o "StrictHostKeyChecking no" -J root@7oaEZMqW
Forwarding SSH traffic from alias "7oaezmqw"
Press g to start a GUI session and ctrl-c to quit.

I suggest installing tmux so you can resume your experiments if you get disconnected. You are root inside the container so you can install anything.

Let me know how it works!


Now read this

Disable hibernation to save space on Windows 8.1 tablet (Toshiba Encore)

If you are in need of more space on your brand new W8.1 tablet you should consider disabling hibernation. It will free up to 2GB on your Hard Drive (on 32GB devices, and even more on 64GB devices), and it’s only downside is that your... Continue →