Get notified on a SSH login

Of course nobody should be able to login to your server. But if someone finds a way to do it, don’t you want to know it?

I am running an Ubuntu Server that uses motd to welcome logged in users. Therefore I am using motd to execute a script for me once a user logged in.

I extracted the details of the just logged in user from /var/log/auth.log, and uses the IP address and a resolver (ipapi.co in my case) to resolve the IP address to a location.

I am using a Telegram Chat with my own Telegram bot to notify me. I might write a small blogpost about my Telegram bot in the future.

Place the script in a file, make it executable, and place it in /etc/update-motd.d/. For example:

$ touch /etc/update-motd/01-notify-me.sh
$ chmod +x /etc/update-motd/01-notify-me.sh
$ vi /etc/update-motd/01-notify-me.sh # Add script 

And the actual script:

#!/bin/bash

_loginDetails=$(grep "Accepted" /var/log/auth.log | tail -n 1)
_IP=$(echo $_loginDetails | awk '{print $11}')
_LOCATION=$(curl https://ipapi.co/${_IP}/json/ | jq .city -r)
_METHOD=$(echo $_loginDetails | awk '{print $7}')
_WHO=$(echo $_loginDetails | awk '{print $4}')
message="[SSH LOGIN] => ${_WHO} from ${_LOCATION}, IP: ${_IP}, AUTH: ${_METHOD}"

curl -s -X POST https://api.telegram.org/<bot_token>/sendMessage -d chat_id=<chat_id> -d text="${message}"

Additional security measures should be taken, for example:

  • Login with Key only
  • Disallow root login via ssh
  • Blacklist IP’s
  • Block based on Geo location
  • fail2ban

2 Reacties

  1. I’m extremely impressed with your writing talents as well as with the layout in your
    weblog. Is this a paid subject or did you modify it your self?
    Either way keep up the excellent quality writing, it is rare to peer a great weblog like this
    one today..

  2. HTML Basic Examples

    12 december 2021 op 16:29

    whoah this blog is famtastic i like studying your articles.

    Stay up the great work! You understand, many persons are searching around for this
    info, you could help them greatly.

Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

© 2025 Roholt

Thema door Anders NorénOmhoog ↑