I'm logging in to a system via SSH and I'd like to be able to force a command to be run on logout, whether that's an intentional logout (exiting the shell) or because my SSH connection has dropped/been terminated. Is there any way to set this up? My best guess right now is to change the login shell to a program that intercepts the signal sent on SSH closing (SIGHUP?) and executes the command then, but I'm wondering if there's a cleaner solution.

  • Do you want to execute the command on the remote-machine or on the one you initialized the connection from?
    – xx4h
    Jun 11, 2014 at 5:50

1 Answer 1


The best way to do this would be to use pam.

In /etc/pam.d you will have several files, one of them will be called sshd. If you only want to affect ssh, and not other logins (such as a GUI, or real TTY), you want this file.
If you want to affect all logins, you'll want a 'common' file. The name of this other 'common' file varies by distro, but you can track it down by following the include and substack statements in the sshd file until you get to the base file.

Once you've identified the file in /etc/pam.d that you want to use, add a line such as the following to the session section:

session     optional    pam_exec.so quiet /etc/pam_session.sh

This will result in calling /etc/pam_session.sh every time someone logs in and logs out (whether gracefully or ungracefully).

Now you just need to create /etc/pam_session.sh. Below is an example you could use to run something every time someone logs out:

if [ "$PAM_TYPE" = "close_session" ]; then

(don't forget to chmod a+x the script)


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .