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
You could simply use
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 :)
@Renik's answer didn't work for me. See below for what did.
This works for me using just the socket file for the control master:
NOTE: You can also use
ssh -S ~/.ssh/<controlfile> ...
as well, which is a bit shorter form of the above.Example
Here's an example where I've already established a connection to a remote server:
And with it disconnected:
If it were still connected, this would force it to exit immediately:
It's unclear to me, but it would appear to potentially be a bug in
ssh
that it requires an additional argument at the end, even thoughblah
is meaningless in the context of the switches I'm using.Without it gives me this:
Version info
OSX CentOS 7.xI confirmed that on both of these versions, the need for the additional bogus argument was required.
References
I wrote a utility that eases management of SSH ControlMaster connections. It's called
cmc
: TimidRobot/cmc: ControlMaster Controller - Eases management of SSH ControlMaster connections.My current approach is to use
lsof
to find the Unix sockets. If I know the target filename specified byControlPath
I can search for the master process like this:This will then give me the
PID
(unfortunately, giving the filename of the unix socket file directly tolsof
doesn't work otherwise I could just ask it to output me thepid
with-f
; hence thesed
andcut
)Searching for the child process is more tricky. The master process opens a new socket for each child process, connected to the standard file. The child process contains a socket simply marked
socket
. However, the inode returned bylsof
is one less than the corresponding master process socket. So the following finds child processes that are connected to the master process (this needs the$MASTER_PID
to check against)