Getting your server to send an email whenever anyone logs in

Running on a VPS like Linode give me plenty of control over what is run, and also plenty of chances to learn more about network administration (along with the heartaches). 😛

The code that I used was based from this forum post. This one presumes that your MTA has been setup properly. The original code was for protecting your root account (i.e. when anyone logs into your server’s root account, you get the notification).

(Note: it is usually not advisable to login as root. Create a user account and give it sudoer rights instead. I’d say that’s advisable even for servers where there is only one person expected to login, which is you.)

[Edit: a more powerful, updated version of this script can be found here]

Protect only the root account

If you want to protect only the root account, edit the file /root/.bash_profile or /root/.profile (the bash profile file takes precedence)

Add this line at the end:
echo 'ALERT - Root Shell Access on:' `date` `who` | mail -s "Alert: Root Login from `who | awk '{print $6}'`" youremailaddresshere

Protect all accounts

If you want to protect ALL accounts, which is better for high security requirements, or for paranoid people like me, you edit the /etc/profile file instead. (you will need root priviledges for this)

For me, I used this instead of the previous command:
echo 'ALERT - Shell Access:' `date` `who` | mail -s "Alert: Shell Access from `who | cut -d"(" -f2 | cut -d")" -f1`" youremailaddresshere

With this, you’ll get a notification whenever anyone logs in. The downside to this is that you may get too many emails on a server that has plenty of people logging in.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s