Skip to content

Instantly share code, notes, and snippets.

@alloc33
Last active June 7, 2025 14:06
Show Gist options
  • Select an option

  • Save alloc33/35a5bde2e02da274679bbc1e7a876400 to your computer and use it in GitHub Desktop.

Select an option

Save alloc33/35a5bde2e02da274679bbc1e7a876400 to your computer and use it in GitHub Desktop.
ngrok-ssh-monitor
#!/bin/bash
EMAIL="[email protected]"
APP_PASSWORD="gmail app pass"
# Check if ngrok is already running
if pgrep -f "ngrok tcp 22" > /dev/null; then
exit 0
fi
# Kill ngrok process
for pid in $(pgrep ngrok); do
if ps -p "$pid" -o cmd= | grep -q "^ngrok"; then
kill "$pid" 2>/dev/null
fi
done
sleep 3
# Set auth token and start ngrok
nohup ngrok tcp 22 >/dev/null 2>&1 &
# Wait for ngrok to initialize
sleep 5
# Get tunnel info and send email
TUNNEL_URL=$(curl -s http://localhost:4040/api/tunnels 2>/dev/null | grep -o '"public_url":"tcp://[^"]*' | cut -d'"' -f4)
if [ -n "$TUNNEL_URL" ]; then
# Extract host and port from tcp://host:port
HOST=$(echo "$TUNNEL_URL" | sed 's|tcp://||' | cut -d':' -f1)
PORT=$(echo "$TUNNEL_URL" | sed 's|tcp://||' | cut -d':' -f2)
# Send email notification
python3 -c "
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('Your Mac Mini SSH is ready!\n\nConnect with:\nssh -p $PORT $USER@$HOST\n\nHost: $HOST\nPort: $PORT')
msg['Subject'] = 'SSH Tunnel Active'
msg['From'] = '$EMAIL'
msg['To'] = '$EMAIL'
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('$EMAIL', '$APP_PASSWORD')
server.send_message(msg)
server.quit()
except:
pass
"
fi
# exec service
# [Unit]
# Description=Ngrok SSH Monitor
# After=network.target
#
# [Service]
# Type=forking
# ExecStart=/usr/local/bin/ngrok-ssh-monitor.sh
# User=root
# KillMode=none
#
# [Install]
# WantedBy=multi-user.target
# timer service
# [Unit]
# Description=Run ngrok monitor every 2 minutes
# Requires=ngrok-monitor.service
#
# [Timer]
# OnBootSec=1min
# OnUnitActiveSec=2min
#
# [Install]
# WantedBy=timers.target
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment