I do something similar on my servers. The general gist of it is this
1) Add to /etc/pam.d/login at the bottom of the session items:
session optional pam_exec.so quiet /etc/pam_session.sh
2) Then create /etc/pam_session.sh as (and chmod +x):
#!/bin/bash [[ "$PAM_USER" == "root" ]] && exit 0 SESSION_COUNT="$(w -h "$PAM_USER" | wc -l)" if (( SESSION_COUNT == 0 )) && [[ "$PAM_TYPE" == "close_session" ]]; then pkill -u "$PAM_USER" fi
If you want, you could add something like sleep 5; pkill -9 -u "$PAM_USER" after the pkill to ensure that it's really dead.
This will only get invoked when login shells exit, so it wont affect automated system activity. However if you want to be even safer, you could add a check for something like the UID being greater than 1000.
ulimit.