Monitoring who accesses your Linux server is a fundamental aspect of system security. While checking the auth.log file is standard practice, reviewing logs is a reactive measure. For immediate situational awareness, you can configure your Ubuntu server to send an instant push notification to your phone via the Telegram messenger API the exact second a user successfully authenticates via SSH.
Setting Up a Telegram Bot
To send messages programmatically, you must first create a Telegram Bot and obtain its API token and your personal Chat ID.
- Open the Telegram app on your phone or desktop.
- Search for BotFather (the official Telegram bot creator) and start a chat.
- Send the message
/newbot. - Follow the prompts to name your bot and choose a unique username ending in “bot”.
- BotFather will reply with an HTTP API Token (e.g.,
123456789:ABCdefGHIjklmnoPQRstuvWXYZ). Copy and save this token securely. - Next, search for userinfobot in Telegram and start a chat to discover your personal account ID. It will reply with your ID number (e.g.,
987654321). Save this ID. - Finally, send a generic message (like “Hello”) to your newly created bot to initialize the chat session.
Creating the Notification Script
With your bot configured, you need to create a simple Bash script on your Ubuntu server that leverages curl to send the API request.
- Log into your Ubuntu server via SSH.
- Ensure
curlis installed by running:sudo apt update && sudo apt install curl -y - Create a new script file in a secure system directory:
sudo nano /usr/local/bin/ssh-telegram-alert.sh - Paste the following code into the file:
#!/bin/bash TOKEN="YOUR_API_TOKEN_HERE" CHAT_ID="YOUR_CHAT_ID_HERE" MESSAGE="🚨 *SSH Login Alert* 🚨%0A%0A*User:* $USER%0A*Host:* $HOSTNAME%0A*IP Address:* $SSH_CLIENT" curl -s -X POST "https://api.telegram.org/bot$TOKEN/sendMessage" -d chat_id=$CHAT_ID -d text="$MESSAGE" -d parse_mode=Markdown > /dev/null - Replace
YOUR_API_TOKEN_HEREandYOUR_CHAT_ID_HEREwith the values you obtained earlier. - Save the file (
Ctrl+O, Enter) and exit the editor (Ctrl+X). - Make the script executable:
sudo chmod +x /usr/local/bin/ssh-telegram-alert.sh
Triggering the Script on Login
To execute this script automatically whenever a user logs in, we must append it to the global shell profile.
- Open the global profile configuration file:
sudo nano /etc/profile - Scroll to the very bottom of the file and add the following lines:
if [ -n "$SSH_CLIENT" ]; then /usr/local/bin/ssh-telegram-alert.sh fiNote: The
ifstatement ensures the alert only triggers for remote SSH logins, ignoring local terminal sessions. - Save and exit the file.
Log out of your server and log back in. Within seconds, your phone will receive a Telegram message detailing the username and IP address of the successful SSH connection, providing you with real-time security alerts.