Linux – How to tell if an ssh ControlMaster connection is in use

daemonlinuxnetworkingsshtunneling

I'd like to use ssh's ControlMaster feature to share connections for speed increases. I'm trying to script it so that I can start/restart/stop a number of connections to different hosts.

How can I determine whether any of these connections are in use? If I kill them when an ssh session is open, it gets closed

My restart script would ideally look like (pseudo-script) – the stop script would be equivalent without the ssh command at the bottom:

for HOST in $HOST_LIST
  do
    MASTER_PID=`find_master_pid $HOST`
    if $MASTER_PID
      then
        if `find_child_pid`
          echo Connection to $HOST in use: not terminating
        else
          kill -SIGHUP $MASTER_PID
        fi
    ssh -TMNf $HOST

Best Answer

You could simply use

ssh -o ControlPath=$socket -O check 

for each $socket you've open (easy if you keep them in a single directory).

This returns 255 if the check fails (connection not active anymore), an other value if it pass. You may need to specify the hostname too, but nothing that an awk on $socket won't give you :)