I am developing a small daemon program which needs to run some instructions when a user logs onto the system (all kinds of logins included). In order to do so, I want my program to be woken up whenever this login event occurs. However, I don't want it to check periodically whether a new user arrived, which means it must not:Read log files such as /var/log/auth.log periodically. Besides the fact that I would have to actually parse the file, I would also probably do it far too often (since there are very few logins on my system).Check the output of another command such as ps, who or w and keep track of users internally. Using this method, the program could miss some logins, in case someone logs in and out before my program runs its checks on the output.Since I don't want my program to waste time, I thought about using I/O events, however... I don't quite see where to hook. I have tried watching over /var/run/utmp (using inotify) but it doesn't seem to react correctly: my program receives a lot of events when terminals are opened/closed, but very few when someone actually logs in (if any at all). Additionally, these events are hardly recognisable, and change from a login attempt to another. For the record, here is a little set of what I was able to catch when running su user:When a terminal opens: IN_OPEN (file was opened), IN_CLOSE_NOWRITE (unwrittable file closed), sometimes IN_ACCESS (file was accessed, when using su -l).When su is started (password prompt): a few events with no identifier (event.mask = 0).After a successful login attempt (shell started as another user) : nothing.When closing the terminal: another set of unnamed events.Is there another way to hook a program onto user logins? Is there a file reflecting user logins on which I could use an inotify watch (just like I could use one on /proc to detect process creations) ? I had another look at /proc contents but nothing seems to be quite what I need.Side note : I thought about posting this on Stack Overflow since it is programming-related, but beyond implementation, I am more interested by the visible reactions a Linux system has when a user logs in (by visible, I mean reactions we could observe/detect/watch out for, programmatically, without wasting time).
How can I detect a user login programmatically?
users;login;inotify
Does your system use Pluggable Authentication Modules (PAM)? Most modern Linux or BSD use PAM.PAM allows you to hook into logins. There are a variety of PAM modules available which might meet your needs, or you can write your own in C. There is even a pam-python* binding which allows you to hook in Python code.Given that you want the daemon to be running continuously, I would opt for a simple PAM module which logs to a file and signals the daemon.*The package is named libpam-python under Debian and Ubuntu. 