Add temporary entry to hosts, when tunnelling SSH

Solution 1:

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

Solution 2:

My apologies if this is not sufficient for an answer, I don't have enough rep to comment here.

I think /etc/hosts is possibly the best option. I don't know what your teardown process is, but you could add removing the /etc/hosts entry as part of it.
Also I think the port change won't work with a /etc/hosts solution. Can you map localhost:8000 to internal-wiki.example:8000?

Then you could add something like 127.0.1.1 internal-wiki.example to /etc/hosts and remove the line when you stop the tunnel like so: sed -i '' '/127.0.1.1 internal-wiki.example/d' (be sure to test that before running live of course).

This should allow you to use http(s)://internal-wiki.example:8000 in your browser.

It's not a perfect solution, but anything better (such as port mapping) I think would require an http proxy running locally.

For what it's worth, adding and removing host entries is how Parallels makes VMs addressable by hostname. This is added to my /etc/hosts while my xu17 VM is running: 172.20.10.112 xu17.shared xu17 #prl_hostonly shared

Of course running an nginx proxy would handle this nicely, but it might be a bit more setup than you're looking for?
A simpler option with netcat might work depending on the web application.

# make fifo for second nc to transfer response back to first nc
mkfifo /tmp/proxy.pipe
nc -lk 8001 < /tmp/proxy.pipe | nc internal-wiki.example 8000 > /tmp/proxy.pipe

Then when you close the tunnel, you can kill the nc process and delete /tmp/proxy.pipe