1

I would like to start a process as root upon each user login. The motivation beside this is, that the process will work on encrypted home folder of particular user folder.

How can I achieve this?

  • Then shouldn't this be the user's own process? – SailorCire Jan 19 '15 at 16:14
3

If your system uses PAM (most do), you can use the pam_exec module in the session stack. Note that the user won't be logged in until the command finishes; if you want to run something in the background, fork it. Several environment variables provide information about the session. For example:

session optional pam_exec.so seteuid /usr/local/sbin/my-login-process

where /usr/local/sbin/my-login-process contains something like

#!/bin/sh
{
  exec 2>&1 >>"/var/log/my-root-service/$PAM_USER.log"
  echo "$PAM_USER logged in on $PAM_TTY on $PAM_RHOST at $(date)"
  do-something
} &
1

In the /etc/sudoers file (shortcut visudo) add these lines:

Cmnd_Alias   CMDNAME = /path/to/binaryOrscriptToBeRunAsRoot
%groupnamehere ALL=NOPASSWD: CMDNAME

Instead of using a username only, creating a CMDNAME group and all users in that group have that permission:

groupadd groupnamehere
usermod -G groupnamehere usertoaddtogrouphere

To test this, become the user, and execute the command:

  1. Become the user => su - usernamehere
  2. Check groups user is in => groups
  3. Run command => sudo CMDNAME restart
  4. In case it isn't a global command run => sudo /path/to/binaryOrScript arg

An example of this is:

/etc/sudoers

Cmnd_Alias   TESTME = /usr/local/bin/testme.sh
%cmdgroup ALL=NOPASSWD: TESTME

/usr/local/bin/testme.sh

#!/bin/sh
#netstat can only be run by root on my servers.
#File permissions are 'chmod 700'
netstat -tln |grep :80

/etc/profile

# You need to change 'testme' in the boundry to match the groupname created
# This checks to see if the user who just logged is part of that cmdgroup, 
# if so, it runs whatever is inside.
username=`id -un`
if groups $username | grep &>/dev/null '\btestme\b'; then
        sudo /usr/local/bin/testme.sh
fi

Login to a user of that group and see:

[nonrootuser ~]#
tcp   0  0 :::80          :::*           LISTEN

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.