How can I run a script as root when a user logs in with pam_exec.so (or otherwise)? The script requires information about the user to function.

Problem and Environment

I would like to run a script—/path/script.sh—as root each time a user logs in. I also need to know the user who logged in (as an environment variable or argument to the script, for example). I am on a recent version of CentOS 7.

I am currently editing /etc/pam.d/system-auth and adding the following line:

session     optional     pam_exec.so /path/script.sh

This works fine when I become the user with sudo su, but does not work if I authenticate to the user otherwise (the script must run as root). In other words,

$ su - robot7
/path/script.sh failed: exit code 1

fails while

$ sudo su - robot7
Last login: Thu Jun 14 09:33:56 MDT 2018 on pts/5

works and runs the script as expected with one caveat: the script also runs when users disconnect. The variable $PAM_USER in the second case is the correct username (robot7, not root).

This script will be used in a production environment where users must not be able to disable it and may have different shells; I cannot use scripts like .bashrc or others to run it.

If I set the command in /etc/pam.d/system-auth to run on auth and not session (as suggested by similar questions), it never runs.


Adding seteuid to the pam_exec.so command allows the script to run when the user authenticates (su - robot7), but does not run the script on SSH (which is the primary method with which users log in).


The security context prevented the script from running. The systemd logs suggested the script was failing to run even though all users were permitted to execute it; some security policy didn't like the script's path.

I moved the script to /bin and the errors immediately resolved themselves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.