The ask here is, when a logged-in user logs out of the ssh session, the system must execute a specific script or a command. So it is like configuring a post script or a trigger to perform the desired action when the user is logged out of the ssh session.
This can be easily done with the help of pam module in CentOS/RHEL systems. Follow the steps outlined below to configure the pam module.
1. Add the below entry to the pam configuration file /etc/pam.d/sshd:
# vi /etc/pam.d/sshd session optional pam_exec.so quiet /var/tmp/post_session.sh
Here,
/var/tmp/post_session.sh is our script which will run when the user is logged out.
The /etc/pam.d/sshd configuration file should look like below:
# cat /etc/pam.d/sshd
#%PAM-1.0
auth required pam_sepermit.so
auth substack password-auth
auth include postlogin
# Used with polkit to reauthorize users in remote sessions
-auth optional pam_reauthorize.so prepare
account required pam_nologin.so
account required pam_access.so
account include password-auth
password include password-auth
# pam_selinux.so close should be the first session rule
session required pam_selinux.so close
session required pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed
in the user context
session required pam_selinux.so open env_params
session required pam_namespace.so
####Trigger with user logout #####
session optional pam_exec.so quiet /var/tmp/post_session.sh
####
session optional pam_keyinit.so force revoke
session include password-auth
session include postlogin
# Used with polkit to reauthorize users in remote sessions
-session optional pam_reauthorize.so prepare
2. Now you can configure the post trigger script as per you requirement. For the sake of this post I will just append the time of user logout into a file. For example:
# cat /var/tmp/post_session.sh #!/bin/bash if [ "$PAM_TYPE" = "close_session" ]; then date >> /var/tmp/user_logout.out ## This is the action to be performed when user logs out. fi
3. Grant the execute permission to the /var/tmp/post_session.sh script.
# chmod ugo+x /var/tmp/post_session.sh
4. Verify by logging in and out multiple time and you should get the time of all the logouts added to the file /var/tmp/user_logout.out.