When using SSH VPN tunnelling (-w option), is there a way to know when the tunnel is actually up? I want to use this in a script that automatically sets up the tunnel by running ssh -w then running ifup [1].

The -f option doesn't help because it returns after connecting to the server but before the tunnel is up. Sleeping for a few seconds does work, but it just feels too hacky.

The LocalCommand option seems to work, for example:

ssh -w 0:1 "-oLocalCommand=ifup tun0" "-oPermitLocalCommand=yes" myserver.example.org true

However, the man page says: "The command is run synchronously and does not have access to the session of the ssh(1) that spawned it." Is the above invocation guaranteed to work or was it just luck that LocalCommand was executed after the tunnel is set up?

More importantly, is there a standard way for using ssh -w in scripts?

[1] I'm on Fedora, ifup works because I've set up /etc/sysconfig/network-scripts/ifcfg-tun0 and /etc/sysconfig/network-scripts/route-tun0


So, I see there are two questions here: 1) How to wait for the tunnel to be actually up, or how to know it is actually up. 2) If there is any standard way to configure an ssh tunnel in Fedora.

About 1): I would personally just use something like:

timeout=2 # Wait for two seconds for a reply.
ip= # Use IP address assigned to tunnel endpoint.
while ! ping -W "$timeout" -c 1 "$ip" &>/dev/null; do
  echo "Waiting for tunnel to be up..."
  sleep 0.5
echo "Tunnel is up."

You can get fancier by using a for loop with a configured number of attempts, or pass something like -I tun0 to the ping command to force use of the tun device.

One reason I prefer this approach is that the fact that having the tunnel itself up doesn't necessary mean that communication will happen. There could be packet loss, iptables rules, route configuration errors, ... I would be careful about making sure the script will be killed if it hangs, and ensure all commands that require the tunnel have a timeout / retry strategy.

About 2): I don't know of any out of the box mechanism to configure ssh tunnels in any distro. This doesn't mean they don't exist. In the past, I have use autossh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.