Skip to content

Instantly share code, notes, and snippets.

@danricho
Forked from smartm13/colab2ssh.ipynb
Created January 30, 2022 23:19
Show Gist options
  • Save danricho/4c2fafb4de12b817b727027d01cab74e to your computer and use it in GitHub Desktop.
Save danricho/4c2fafb4de12b817b727027d01cab74e to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Colab to SSH",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "Ftyme-AIYFgK",
"colab_type": "text"
},
"source": [
"#Setup SSH port forwarding"
]
},
{
"cell_type": "code",
"metadata": {
"id": "C0t3EVVaWbUJ",
"colab_type": "code",
"colab": {}
},
"source": [
"#1 - setup ssh/user \n",
"\n",
"\n",
"#Generate a random root password\n",
"import random, string\n",
"password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(30))\n",
"password = 'toor'\n",
"\n",
"#Setup sshd\n",
"! apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen > /dev/null\n",
"\n",
"#Set root password\n",
"! echo root:$password | chpasswd\n",
"! mkdir -p /var/run/sshd\n",
"! echo \"PermitRootLogin yes\" >> /etc/ssh/sshd_config\n",
"! echo \"PasswordAuthentication yes\" >> /etc/ssh/sshd_config\n",
"\n",
"print(\"username: root\")\n",
"print(\"password: \", password)\n",
"\n",
"#Run sshd\n",
"get_ipython().system_raw('/usr/sbin/sshd -D &')"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "H_1iQGAtYvCq",
"colab_type": "code",
"colab": {}
},
"source": [
"# 2 - Download Ngrok\n",
"\n",
"! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n",
"! unzip -qq -n ngrok-stable-linux-amd64.zip"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "68P192JwZBtF",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
},
"outputId": "5d9f789e-4f85-44f3-f642-2522ec728a0e"
},
"source": [
"# 3 - setup Ngrok - authtoken\n",
"\n",
"#print(\"Get your authtokens from https://dashboard.ngrok.com/auth\")\n",
"\n",
"#collection of some working authtokens\n",
"chalu1='1WXO8VheqmW0bly8k3nXZn5PRGd_xEviNuNJmtNNqiAqFyN6'\n",
"chalu2='1WXSLgMGAtFE1xjGcuB8L7r0LKg_PR65aD9WLuBDGhWitA9C'\n",
"\n",
"authtokens = [chalu1,chalu2] # or __import__(\"getpass\").getpass()\n",
"with open(\"/content/ngrok-launch.sh\",'w') as f:\n",
" f.write(\"rm -rf /tmp/ngrok-mic.drop\\n\")\n",
" for autht in authtokens:\n",
" f.write(f\"/content/ngrok authtoken {autht} && /content/ngrok tcp 22 && exit\\n\")\n",
" f.write(\"echo done>/tmp/ngrok-mic.drop\\n\")\n",
"#Create tunnel\n",
"print(\"Launching NGROK\")\n",
"#get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')\n",
"get_ipython().system_raw(\"bash /content/ngrok-launch.sh &\")"
],
"execution_count": 20,
"outputs": [
{
"output_type": "stream",
"text": [
"Get your authtokens from https://dashboard.ngrok.com/auth\n",
"Launching NGROK\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "lLB-CbRnQS_S",
"colab_type": "code",
"colab": {}
},
"source": [
"import os\n",
"port='x'\n",
"while not port[0].isdigit():\n",
" if port!='x':\n",
" print(\"Waiting for ngrok to launch with right key...\")\n",
" port=!curl -s http://localhost:4040/api/tunnels | python -mjson.tool | grep public_url | awk -F: '{print $4}'| rev | cut -c 3- |rev\n",
" if os.path.isfile(\"/tmp/ngrok-mic.drop\"):\n",
" print(\"Ngrok Launch Failed\")\n",
" break\n",
" \n",
"print(f\"Here are your ssh creds:\\nssh root@0.tcp.ngrok.io -p {port[0]}\\n{password}\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "L_qAj6zJRHPm",
"colab_type": "code",
"colab": {}
},
"source": [
"import time\n",
"time.sleep(12*3600)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "ACzGZ2_MaSQi",
"colab_type": "code",
"colab": {}
},
"source": [
"# When done, kill Ngrok\n",
"\n",
"!kill $(ps aux | grep './ngrok' | awk '{print $2}')"
],
"execution_count": 0,
"outputs": []
}
]
}
# -*- coding: utf-8 -*-
"""Colab to SSH
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/gist/smartm13/7978192956e79452f46020c277f53ec7/colab2ssh.ipynb
#Setup SSH port forwarding
"""
#1 - setup ssh/user
#Generate a random root password
import random, string
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(30))
password = 'toor'
run_sh = lambda cmd,retainspace="_space_",toscript=True:((toscript and open("/tmp/toscript.sh",'w').write(cmd)) and not toscript) or (__import__("subprocess").run("sh /tmp/toscript.sh".split() if toscript else [c.replace(retainspace," ") for c in cmd.split()], stdout=__import__("subprocess").PIPE).stdout.decode('utf-8').strip().split("\n"))
#Setup sshd
run_sh("apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server pwgen")
#Set root password
run_sh("echo root:$password | chpasswd".replace("$password",password))
run_sh("mkdir -p /var/run/sshd")
run_sh('echo "PermitRootLogin yes" >> /etc/ssh/sshd_config')
run_sh('echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config')
print("username: root")
print("password: ", password)
#Run sshd
get_ipython().system_raw('/usr/sbin/sshd -D &')
# 2 - Download Ngrok
run_sh("wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip")
run_sh("unzip -qq -n ngrok-stable-linux-amd64.zip")
# 3 - setup Ngrok - authtoken
#print("Get your authtokens from https://dashboard.ngrok.com/auth")
#collection of some working authtokens
chalu1='1WXO8VheqmW0bly8k3nXZn5PRGd_xEviNuNJmtNNqiAqFyN6'
chalu2='1WXSLgMGAtFE1xjGcuB8L7r0LKg_PR65aD9WLuBDGhWitA9C'
authtokens = [chalu1,chalu2] # or __import__("getpass").getpass()
with open("/content/ngrok-launch.sh",'w') as f:
f.write("rm -rf /tmp/ngrok-mic.drop\n")
for autht in authtokens:
f.write(f"/content/ngrok authtoken {autht} && /content/ngrok tcp 22 && exit\n")
f.write("echo done>/tmp/ngrok-mic.drop\n")
#Create tunnel
print("Launching NGROK")
#get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')
get_ipython().system_raw("bash /content/ngrok-launch.sh &")
import os
port='x'
while not port[0].isdigit():
if port!='x':
print("Waiting for ngrok to launch with right key...")
port=run_sh("curl -s http://localhost:4040/api/tunnels | python -mjson.tool | grep public_url | awk -F: '{print $4}'| rev | cut -c 3- |rev")
if os.path.isfile("/tmp/ngrok-mic.drop"):
print("Ngrok Launch Failed")
break
print(f"Here are your ssh creds:\nssh root@0.tcp.ngrok.io -p {port[0]}\n{password}")
with open("/content/ngrok-kill.sh",'w') as f:f.write("kill $(ps aux | grep './ngrok' | awk '{print $2}')")
print("Ending Note: To kill use /content/ngrok-kill.sh")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment