[linux-elitists] Fun* with ssh tunnels
dmarti at zgp.org
Sat Jul 31 08:42:28 PDT 2010
For some reason I often end up thinking about the
problem of doing this in a script: bring up an ssh
tunnel, do something over the tunnel, drop the tunnel.
For example, I send outgoing queued mail from my
laptop over a tunnel to my mail server.
I used to do this something like...
ssh -L 10025:localhost:25 $MAILHOST sleep 5 &
...then sleep on the client to allow for the tunnel to
come up, then do the thing that has to connect over
the tunnel (in this case connect to the configured
"smarthost" which is localhost, port 25.
But this is kind of inelegant and requires tweaking
sleep times. And you get the unavoidable problem
of having to sleep long enough to allow for the
slowest possible time to bring up the tunnel.
So here's what I came up with a little while ago,
and if you're reading this it actually works.
Start an ssh connection to the server with two tunnels
on it. One forwards local port 10025 to the server's
SMTP port, and the other forwards port 10022 on the
server back to the client's ssh port. And instead of
running "sleep" or something on the server to hold the
tunnel open until the flow of data starts, run ssh on
the server, using one tunnel to ssh back to the client
to run the command that has to use the other tunnel.
/usr/bin/ssh -A -L 10025:localhost:25 \
-R 10022:localhost:22 \
/usr/bin/ssh -p 10022 localhost /usr/sbin/postqueue -f
So the "postqueue" command is running on the client.
You need agent forwarding for this to work, and you
need to be able to ssh in to localhost, at least
on lo. (Yes, I run sshd, on lo only, on the client.
Fastest way to do things that need to run as another
user as another user.)
* Your fun level may vary.
dmarti at zgp.org
More information about the linux-elitists