This is a late answer, but you can execute it on every login AND have it run as root (or any other user you want), by doing the following:
- Write your script, with the commands you want to run as root, and save it e.g. as
/path/to/root-script.sh
.
Make root (or the desired user) the owner of the script.
chown root:root /path/to/root-script.sh`
Set the setuid bit on the script, with other desired permissions. (make sure it is not universally writable etc.)
chmod 4755 /path/to/root-script.sh
The 4
means set the setuid bit, which will cause the script to be run as the owner of the script. This is what sudo
uses to ensure execution as root.
To ensure it is run on every login, run the sticky-bit-set root-script.sh
from within /etc/profile
. The /etc/profile
should be run regardless of the shell used by the user. Note this will only apply to interactive logins however.
Edit. As noted by Scott in comments, this solution does NOT generally work on any modern system with any shebang script other than Perl < 5.12.0. Modern kernels would ignore scripts with a setuid bit unless they have been patched, which would not be recommended for security reasons.
Rather, setuid only generally works on compiled binaries and [old versions of Perl][https://stackoverflow.com/questions/21597300/can-i-setuid-for-perl-script]
that can use (Perl <5.12.0) with suidperl
.
This Unix/Linux SE question has thorough answer of why setuid is ignored for shebang scripts, with its summarized TL;DR:
Setuid shebang is insecure but usually ignored. If you run a program
with privileges (either through sudo or setuid), write native code or
perl, or start the program with a wrapper that sanitizes the
environment (such as sudo with the env_reset option).