Add temporary entry to hosts, when tunnelling SSH

hostsmac-osxssh-tunnel

When outside our company firewall, I use a script to tunnel via SSH and expose our internal wiki to my OSX machine. Is there a command to temporarily tell OSX to resolve to my local port when the tunnel is set up?

The sequence I'm hoping to use is:

  1. open the tunnel

    ssh -f external-proxy.example -L 8001:internal-wiki.example:8000 -N
  2. [DO SOMETHING HERE]

  3. typing the URL internal-wiki.example:8000 in my browser causes it to transparently view localhost:8001

Other details:

  • I could edit /etc/hosts but that would be a persistent change. I want to use this only when outside
  • We're not using SSL or certs.

Best Answer

I have a solution for you, wrap your ssh command into a bash script:

#!/bin/bash

function control_c {
    echo -en "\n## Caught SIGINT; Clean up /etc/hosts and Exit \n"
    sed -i '' "/internal-wiki/d" /etc/hosts
    exit $?
}

trap control_c SIGINT
trap control_c SIGTERM

(sleep 5; open http://internal-wiki.example:8001 &)&
echo '127.0.0.1 internal-wiki.example' >> /etc/hosts
ssh -L8001:internal-wiki.example:8000 -f external-proxy.example -N

Explaining:

  1. function that executes the cleanup on Control-C when issued
  2. trap Control-C and shutdown
  3. sleep, tell osx to open your site, get out of the way (the ampersand)
  4. adds the entry to /etc/hosts
  5. create the tunnel
  6. when you ctrl-c, the functions kicks in and cleans up /etc/hosts with the transient entry