Se o seu shell for bash , uma maneira seria usar comandos em ~/.bash_logout . De man bash :
When a login shell exits, bash reads and executes commands from the file
~/.bash_logout, if it exists.
O SSH executa um shell de login, portanto, quando ele sair, .bash_logout deve ser executado. Você pode verificar se é uma sessão SSH testando o valor da variável SSH_TTY . Então você pode editar (ou criar) ~/.bash_logout contendo, por exemplo:
if [[ -n $SSH_TTY ]]
then
stop your service
fi