Featured image of post 開自動啟動 ngrok ssh 連線並在 Cloudflare 取得登入 URL 及 PORT

開自動啟動 ngrok ssh 連線並在 Cloudflare 取得登入 URL 及 PORT

📌 Introduction

我有一台在內網的機器,每當重開機時,需要 SSH 連線到機器。

可以先在機器上安裝 ngrok,並設定開機自動啟動,再透過 CLoudflare Worker 讀取 ngrok 的 API 來顯示

Automatically start ngrok SSH connection and obtain the login URL and PORT from Cloudflare.

I have a machine on the internal network, and every time it restarts, I need to SSH into the machine.

First, install ngrok on the machine and set it to start automatically on boot. Then, use a Cloudflare Worker to read the ngrok API and display the information.

📝 Steps

1. 建立 ngrok.sh 放在家目錄底下,開機時可以被 crontab 執行

Create ngrok.sh and place it in the home directory so it can be executed by crontab at startup.

#! /bin/bash

ngrok tcp 22 --log=stdout > /tmp/ngrok.log &

2. 用 crontab -e 編輯 crontab 腳本

Use crontab -e to edit the crontab configuration.

# 新增在最後一行
@reboot ~/ngrok.sh

3. 編輯 Cloudflare 的 Worker,可以從 https://dashboard.ngrok.com/api 看到 API Key

Edit the Cloudflare Worker, and you can see the API Key at https://dashboard.ngrok.com/api.

export default {
  async fetch(request, env, ctx) {
    let response = await fetch("https://api.ngrok.com/endpoints", {
      headers: {
        "Authorization": "Bearer XXXXXXXXXX",  // 這行需要更改
        "Ngrok-Version": "2"
      },
    });
    let endpoints = JSON.parse(JSON.stringify(await response.json()));
    
    if (endpoints['endpoints'].length > 0) {
      var re = "";
      for (let i = 0; i < endpoints['endpoints'].length; i++) {
        re = re + endpoints['endpoints'][0]['public_url'] + " " + endpoints['endpoints'][0]['created_at'] + "\n";
      }
      return new Response(re);
    } else {
      return new Response("");
    }
  },
};