SSH to Google Colaboratory with Serveo.net
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:
Open a new Colab notebook (you can name it ssh for future use)
Set your runtime to Python 3 and GPU (optional)
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 serveo.net root@{}'.format(password, alias))
! ssh -o "StrictHostKeyChecking no" -R $alias:22:localhost:22 serveo.net
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 serveo.net 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!