Run script after a SSH client disconnects

84 views Asked by At

I am trying to research for possible solutions on how to execute a script on FreeBSD after a SSH client disconnects. I have found numerous solutions, but all but one actually deal with a different problem "how to keep the client's script running even if the client disconnects". I don't want that. I really do want to run a different script after the user disconnected; particularly, I will want to calculate a SHA256 hash of all files, compare the differences against the previous version and mail it to the administrator.

The only solution that I found that seems to do what I want is https://stackoverflow.com/a/57004045/6755416 , but it is rather sketchy (e.g. the question it references no longer contains the background information) and I am not at all sure it can be applied to my use case (in particular, PAM authentication is disabled for my sshd and I want to keep it disabled).

On the other hand, my use case doesn't require an immediate reaction. I would be perfectly fine to e.g. run a script every 15 minutes using cron, somehow detect whether a SSH client session had terminated since the last check, and if so, perform whatever actions I need. Also, there will only be a few user accounts where I need the script performed and these will be configured manually; furthermore, the users will attempt to cooperate (I am more concerned about the user forgetting to execute the cleanup than with dealing with a malicious user).

What are my options here, please?

1

There are 1 answers

2
Romeo Ninov On

If you use bash you can add in home directory of user file .bash_logout which will be executed when the user gracefully logout from the system. For csh/tcsh the file is .logout

Nongracefull version can be done for example via cron script which check for list of users and compare username with old list (from previous execution) and do appropriate actions.

But in both cases you may have situation when user logout and seconds later login again and start editing. So the your hashes will fail for some files.