Bash SSH Tunnel Wrapper
I recently became the caretaker of a Chef server that sits behind a firewall, inaccessible to all but the nodes that require access. Even though it’s locked down, I still need to be able to administer it. My tool of choice is knife, the command-line utility used to interact with Chef.
I have SSH access to the box, so to use knife I only have to create an SSH tunnel:
ssh -T -f -N -L 4000:localhost:4000 dryan@chef.example.com
This works, but I don’t really want to manually manage SSH tunnels. What I really want is a wrapper that 1) creates the tunnel 2) runs my command, and 3) closes the tunnel. So I wrote a bit of Bash to allow me to do just that:
function create_chef_tunnel() {
cmd='ps -eo pid,args | egrep "[s]sh -T -f -N -L 4000:localhost" | cut -c1-6'
if [ $? -eq 0 ]
then
echo "SSH tunnel exists"
return
else
ssh -T -f -N -L 4000:localhost:4000 dryan@chef.example.com
fi
}
function close_chef_tunnel() {
cmd='ps -eo pid,args | egrep "[s]sh -T -f -N -L 4000:localhost" | cut -c1-6'
pid=$(eval $cmd)
kill -9 $pid
}
function chef_tunnel_wrapper() {
create_chef_tunnel
"$@"
close_chef_tunnel
}
alias knife="chef_tunnel_wrapper knife"
Surely, the above snippet could be made more re-usable. One could modify it to support specifying ports, hosts, usernames, etc, but I didn’t need it for anything else just yet. I’ll leave that as an exercise to the reader :)