Archive for the ‘Bash’ category

Email notification on root SSH login

February 26th, 2010

If you are looking to add a little more security to SSH on your server, one thing you can do is setup an email notification on any root login onto your server.

To do this you will need to log in as root on SSH and then run the list command:
ls

You should see a list that includes several bash files like .bash_history, .bash_logout and .bash_profile. To add this notification alert, we are going to add a bash script to .bash_profile.

However, the file cannot be saved to as is as you will receive the following error “[ Error writing .bash_profile: Permission denied ].” This error is because the file is immutable. To resolve this we will run the following command before opening up .bash_profile:
chattr -i .bash_profile

Next we will run this command so that we can add our little bash script:
pico .bash_profile

Here is the bash script you will add. You can change it to fit the message you went sent to your email address. At the end of it you see root. This is the email account that it will be sending to, so you should make sure you have an email account setup in WHM as this is where it will forward it to.

# Email admin when user logs in as root
rootalert() {
echo "Greetings,"
echo
echo "This email is an alert automatically created by your server telling you that someone, even if it is you$
echo
echo "The following information is currently who is logged in to your server right now."
echo
echo "Server: "`hostname`
echo "Time: "`date` echo printf "$(w)" echo echo echo "------" echo "Holdfire, LLC - Root Login Notifier" echo
}
rootalert | mail -s "SSH Root Login [Server: `hostname`][IP: `hostname -i`]" root

To save the file you will type in CTRL + X yes to save the changes and voila.

To set .bash_profile back to immutable you will run.
chattr +i .bash_profile