Question
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
Password:
/path/script.sh failed: exit code 1
-bash-4.2$
fails while
$ sudo su - robot7
Last login: Thu Jun 14 09:33:56 MDT 2018 on pts/5
-bash-4.2$
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.
Edit
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).