Contents

Auto Start SSH Tunneling on Mac

Prerequisites

Skip this step if you have it.

Install Homebrew :

1
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Install SSH-Key using Keygen :

1
ssh-keygen -t rsa

Add SSH-Key fingerprint into the tunneling :

1
ssh -nNt -D port username@host

Step to auto connect SSH Tunneling

  1. Install sshpass using Homebrew
1
brew install hudochenkov/sshpass/sshpass
  1. Create file ~/scripts/startup/startup.sh to connect ssh tunneling automatically, and type code like below.
1
2
3
4
5
6
7
8
#!/bin/bash
#Start SSH Tunneling on IST Yogyakarta if is not running
 
echo "Entering SSH Tunneling"
 
sshpass -p "your_password" ssh -nNt -D port username@host
 
echo "Connection closed!"
  1. Type chmod +x ~/scripts/startup/startup.sh on your terminal to change the file can be execute.

  2. Create file ~/Library/LaunchAgents/com.startup.plist to run startup.sh automatically when the laptop is starting, and type code like below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>EnvironmentVariables</key>
    <dict>
      <key>PATH</key>
      <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:</string>
    </dict>
    <key>Label</key>
    <string>com.startup</string>
    <key>Program</key>
    <string>/Users/your_username_laptop/scripts/startup/startup.sh</string>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/startup.stdout</string>
    <key>StandardErrorPath</key>
    <string>/tmp/startup.stderr</string>
  </dict>
</plist>
  1. Create file ~/reload.sh to handle when disconnected from tunnel and type code like below.
1
2
3
4
5
6
7
8
9
#!/bin/bash
#Start SSH Tunneling on IST Yogyakarta if is not running
 
echo "Reloading SSH..."
 
launchctl unload -w ~/Library/LaunchAgents/com.startup.plist
launchctl load -w ~/Library/LaunchAgents/com.startup.plist
 
echo "Done Reload!"
  1. Type chmod +x ~/reload.sh on your terminal to change the file can be executed.

  2. Type launchctl load -w ~/Library/LaunchAgents/com.startup.plist to run startup agent.

  3. Setup your browser with proxy SOCKS port forwarding. If you using Chrome, you can use SOCKS plugin and forward it to tunneling port.

Thankyou

Medium - Adding Startup Scripts to Launch Daemon

SSHPASS - SSHPASS non Interactive SSH Login Shell Script SSH Password