Kill backgrounded SSH when shell exits

I’m trying to spawn an SSH from my bash profile script that runs in the background for connection sharing (via its control socket). The problem I’m running into is a reliable way to ensure the SSH doesn’t stay running once the TTY is closed (or more directly; once the parent bash shell has exited).

I know the shell can run commands (to terminate SSH) when it exits gracefully, but I’m trying to handle all possible scenarios where the shell doesn’t get a chance to shut things down.

Is there a clever way I can do this?

The best idea I’ve had is

ssh -o PermitLocalCommand=yes -o LocalCommand='cat >/dev/null; kill $PPID' $HOST &

But this won’t work because I need the command to only background once it has successfully started. Alternatively, I can’t use -fN instead of the shell’s & because the SSH -f only backgrounds after the LocalCommand has completed.

Also I’m trying to avoid running any command on the remote host. Otherwise I could probably do something like ssh -fN $HOST 'cat >/dev/null'

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If your shell is a login shell you can stop SSH master connection from ~/.bash_logout file:

ssh -O exit hostname

If the shell isn’t a login shell you can set a trap in your ~/.bashrc file just after spawning SSH:

ssh -fN hostname
trap 'ssh -O exit hostname' EXIT

Method 2

I hate it when I answer my own question.

The solution I came up with is to use ControlPersist=3600 when starting the master ssh process. This way if the shell doesnt exit gracefully and kill ssh, then it’ll shut itself down after an hour of inactivity. Though I still use a trap on exit to shut ssh down cleanly.

ssh -o ControlMaster=yes -o ControlPersist=3600 -o ControlPath=/tmp/ssh-%u-%h-%p-%r -Nf $HOST
trap "ssh -o ControlPath=/tmp/ssh-%u-%h-%p-%r $HOST -O exit" exit

Method 3

Keep SSH Sessions running after disconnection

I don’t know if this is what you are looking for but it helped me keep my program running after exiting the ssh shell.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x