Check process of a single SSH tunnel in a shell script?
My thoughts:
- Pid files. I think this is a general approach.
-
XY problem, use
autossh
.
(Some other answers may elaborate these ideas.)
-
There are two scripts, right? (not exactly complying with DRY). Give them different names. Your script waits for its
ssh
to exit. The additional instance, instead of checking pid(s) ofssh
, should check pid(s) of its own name. Exactlyone pidtwo pids mean no previous script is still running:[ $(pidof -x scriptname | wc -w) -eq 2 ] && createTunnel
Why two? Because
$()
starts a subshell that also counts. Quite dirty, oh well. -
Somewhat outside-the-box, I think. Create two symlinks with unique names, like:
ln -s /usr/bin/ssh ssh-foo ln -s /usr/bin/ssh ssh-bar
Let the first script run
ssh-foo
, let the second runssh-bar
. Theirpidof
invocations should targetssh-foo
orssh-bar
respectively as well. This way they won't mix. As a bonus, additionalssh
(possibly run for a completely different reason in the future) won't affect them.
And finally:
-
You don't have to check anything.
/usr/bin/ssh -o ExitOnForwardFailure=yes -N -R :2222:localhost:22 [email protected]
If the tunnel already exists, port forwarding will fail for sure and
ssh
will exit. I guess you can run this line directly from a crontab, no script is required.