The Secure Shell Protocol (SSH) is probably one of the most known and used remote administration tool. It can be configured to allow password authentication as well as public-key authentication, where the latter usually offers more resilience against automated Internet bots trying to gain unauthorized access.
Furthermore, there are various tools to additionally secure the SSH service such as Fail2ban or Crowdsec. These Intrusion Detection System (IDS) solutions actively monitor SSH log data to identify a vast of failed login attempts and ban the IP addresses of threat actors. But what about valid SSH logins?
On today's blog post we will focus on implementing an alerting feature for successful SSH logins. Whether it is an unauthorized threat actor or just yourself gaining SSH access during regular server administration. We will plant a shell script that notifies us via Telegram about successful SSH logins on our server.
Setup and Installation
There are various options to choose from in order to implement notifications during SSH logins. Various other blog posts will often recommend putting a bash script at
/etc/profil.d/. However, this solution is not bullet proof, as an attacker may login via SSH using
/bin/bash. If this is the case, scripts located at
/etc/profil.d/ are not executed.
If you want a more bullet-proof approach, I recommend following the second option, utilizing a PAM exec module.
Option 1: /etc/profil.d/
All you need to do is to save the following bash script
ssh-telegram.sh at the path
/etc/profil.d/ of your Linux server and also install the lightweight JSON processor tool
jq, which is used in the script itself. Also adjust the
KEY variable with your Telegram API token and user's chat ID.
sudo chown root:root <sh-file> sudo chmod -R 755 <sh-file>
Option 2: PAM Module
A more robust way of obtaining notifications is using PAM (Pluggable Authentication Modules). It has a module named pam_exec to execute a script at specific PAM events, such as a successfull SSH login.
It's adviced to adjust the above script slightly. Then just place it at your prefered location, not being
/etc/profil.d/, e.g. at
Afterwards, put the following lines of code inside the file
As soon as a successful SSH login occurs, the notification script will be executed and sends a Telegram notification to you. It will disclose various helpful information to you, such as the user that logged in, the remote IP address from which the login occurred as well as specific information about the IP address itself (city, region, country, organization), if available.
A notification will look something like this: