Skip to content

Instantly share code, notes, and snippets.

@ivansaul
Created March 4, 2021 03:01
Show Gist options
  • Save ivansaul/14f295a8ebd17de421681cd77bd8bfc8 to your computer and use it in GitHub Desktop.
Save ivansaul/14f295a8ebd17de421681cd77bd8bfc8 to your computer and use it in GitHub Desktop.
How to connect to google colab with ssh from terminal
  1. You need to create an account on ngrok.com.
  2. Copy and paste below code in colab.
#@markdown <br><center></center>
#@markdown <center><h2>SSH Google Colab</h2></center><br>

#CODE
#Generate root password
import random, string
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(5))
password = password.lower()
#Download ngrok
! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
! unzip -qq -n ngrok-stable-linux-amd64.zip
#Setup sshd
! apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen > /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 "export LD_LIBRARY_PATH" >> /root/.bashrc

#Run sshd
get_ipython().system_raw('/usr/sbin/sshd -D &')

#Ask token
print("Copy authtoken from https://dashboard.ngrok.com/auth")
import getpass
authtoken = getpass.getpass()

#Create tunnel
get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')
#Print root password
print("Root password: {}".format(password))
print("You can connect to colab server on terminal with following command:")
#Get public address
! curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'].replace('tcp://','ssh root@').replace(':',' -p '))"    
  1. Now, in your local machine. Open a terminal and type the output from step 2, something like ssh [email protected] -p 19377
  2. You will be asked to enter root password. See step 2 output.
  3. Thats all! Now you have access to the whole system through SSH terminal.

Code was taken from this sources: [1] [2]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment