Park Golf Side Image

Get Linux To Notify You Of Every ssh Login

Sometimes you just want something simple. Here’s how you can be notified every time someone logs into a Linux system via ssh (Secure Shell). We’ve assumed that your users run the bash shell, but the same principle can be adopted for other shells.


Put the following in /etc/profile:
if [ -n "$SSH_CLIENT" ]; then
    TEXT="$(date): ssh login to ${USER}@$(hostname -f)"
    TEXT="$TEXT from $(echo $SSH_CLIENT|awk '{print $1}')"
    echo $TEXT|mail -s "ssh login" you@your.domain

How it works

The script /etc/profile is executed at every login (for bash shell users). The if statement will only return true if the user has logged in via ssh, which in turn will cause the indented code block to be run. Next, we then build the text of the message:
  • $(date) will be replaced by the output of the “date” command
  • ${USER} will be replaced by the user’s login name
  • $(hostname -f) will be replaced by the full hostname of the system being logged into
  • The second TEXT line adds to the first, giving the IP address of the system this user is logging in from.
Finally, the generated text is sent in an email to your address.


Linux will, by default, record every system login, whether by ssh or not, in the system log files, but sometimes – particularly for a system that is seldom accessed via ssh – a quick and dirty notification can be useful.

Related Articles: