E-Mail alert on ROOT login

I was just recently asked this again by a collegue. Once again he ran into one of many „howto“s which does not quite have it right. Why those howtos are listed on TOP at Google I have no clue, but let’s explain this and get this right once and for all.

Many howtos I have looked at tell you to put something in /root/.bashrc … bla bla bla.

The big problem with that is, that if someone just executes a direkt command and does not log in (no need to load the „.bashrc“) or he logs in with „ssh root@example.com /bin/bash --noprofile --norc“ (again no loading of the .bashrc) no e-mail will be triggered.

So these examples are nice if you want to get a mail if you yourself log in as root or one of your collegues does. I nother words, no pointin doing it.

So what do you do instead? You creat and put it into a file called /root/.ssh/rc … this will get called no mather what. No one can go in as root without loading this, it is not shell specific, just specific to root and ssh.

What do we put in there again?

echo 'Root Shell Access on Server XYZ on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`" me@mymail.de

That would be an example, you can modify it as you like of course.