UbuntuUbuntu Based

How To Enable SSH Login Alerts on Ubuntu 24.04 LTS

Enable SSH Login Alerts on Ubuntu 24.04

Server security remains a critical concern for system administrators and DevOps professionals managing Ubuntu infrastructure. SSH (Secure Shell) access, while essential for remote server management, represents a primary attack vector for unauthorized access attempts. Implementing SSH login alerts provides an immediate notification layer that detects both legitimate access and potential security breaches in real-time. This comprehensive guide explores multiple notification methods—email, Telegram, and Slack—enabling monitoring solutions tailored to different operational environments. Whether managing a single VPS or enterprise infrastructure, SSH login alerts form an indispensable component of proactive security monitoring.

Why SSH Login Alerts Matter for Ubuntu 24.04 LTS

SSH-enabled servers face constant threats from automated brute-force attacks, credential stuffing campaigns, and sophisticated intrusion attempts. Real-time login notifications serve multiple security functions: immediate detection of unauthorized access attempts, creation of comprehensive audit trails for compliance requirements, and early warning systems for compromised credentials.

Ubuntu 24.04 LTS provides enhanced compatibility with modern notification systems and mail transfer agents, making alert implementation more streamlined than previous releases. Security professionals recognize that alerts work synergistically with other hardening measures like fail2ban intrusion prevention, key-based authentication enforcement, and firewall configurations.

Different notification channels suit different operational contexts. Email alerts remain standard for traditional enterprise environments with established mail infrastructure. Telegram notifications offer lightweight, mobile-first alerting perfect for solo administrators and small teams. Slack integrations excel in DevOps environments where teams already collaborate through messaging platforms. The choice depends on existing workflows, team size, and response time requirements.

Prerequisites and System Requirements

Successful SSH alert configuration requires specific system components and access levels. An Ubuntu 24.04 LTS server—either fresh installation or system upgraded from previous LTS releases—provides the foundational environment. Administrative access through root account or user with sudo privileges remains essential for system-wide configuration changes.

Verify SSH server installation and operational status:

sudo systemctl status ssh

The command should return active status. If SSH requires installation, execute:

sudo apt update
sudo apt install openssh-server

Basic command-line proficiency and familiarity with terminal-based text editors (nano or vi) enables effective configuration. Network connectivity allowing outbound connections for email delivery or API communications (Telegram, Slack) must exist. Firewall rules should permit necessary traffic while maintaining security posture.

Package installation requirements vary by notification method but commonly include postfix (mail transfer agent), mailutils (mail command utilities), and curl (API communications). Before making configuration changes, create backups of existing SSH configurations and shell profile files.

Understanding SSH Login Alert Mechanisms

SSH login notifications leverage shell initialization scripts that execute automatically when users establish remote connections. Ubuntu and Debian-based distributions primarily use .bashrc files located in user home directories, while some systems employ .bash_profile or .profile alternatives. Understanding execution timing proves crucial—these scripts run after successful SSH authentication but before presenting the command prompt.

The SSH_CONNECTION environment variable captures critical session information including client IP address, connection port, server IP, and SSH port. Notification scripts extract this data, combine it with system information (hostname, username, timestamp), and transmit alerts through configured channels.

Alert implementation occurs at different privilege levels. User-specific alerts modify individual .bashrc files in home directories (/home/username/.bashrc for regular users, /root/.bashrc for root). System-wide monitoring requires configuration in /etc/profile.d/, affecting all user logins.

PAM (Pluggable Authentication Modules) provides an alternative trigger mechanism offering more reliable execution independent of shell configuration. PAM integration ensures notifications fire even when users employ non-bash shells or custom profile configurations.

Performance impact remains minimal on typical systems, as notification scripts execute lightweight operations. High-traffic servers with numerous concurrent SSH sessions may benefit from asynchronous notification delivery to prevent login delays.

Method 1: Setting Up Email Notifications

Installing and Configuring Mail Services

Email-based SSH alerts require functional mail transfer agent configuration on Ubuntu 24.04 LTS. Postfix provides reliable, widely-supported MTA functionality suitable for this purpose.

Install Postfix and mail utilities:

sudo apt update
sudo apt install postfix mailutils

During installation, select “Internet Site” configuration when prompted. Enter the fully qualified domain name (FQDN) for the mail server hostname—typically matching the server’s hostname or domain name.

For servers without direct mail delivery capability, configure Postfix to relay through external SMTP services. Gmail relay setup requires editing /etc/postfix/main.cf:

sudo nano /etc/postfix/main.cf

Add or modify these lines:

relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt

Create credential file /etc/postfix/sasl_passwd:

sudo nano /etc/postfix/sasl_passwd

Add Gmail credentials (use app-specific password, not account password):

[smtp.gmail.com]:587 your-email@gmail.com:app-password

Secure and process the credential file:

sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd
sudo systemctl restart postfix

Test email functionality before implementing alerts:

echo "Test email from Ubuntu server" | mail -s "SSH Alert Test" your-email@example.com

Check inbox (and spam folder) for received message.

Configuring Email Alerts in .bashrc

Email alerts trigger automatically by adding notification scripts to bash profile files. For root user monitoring, edit /root/.bashrc:

sudo nano /root/.bashrc

Add this script at the file’s end:

# SSH Login Email Alert
if [ -n "$SSH_CONNECTION" ]; then
    IP=$(echo $SSH_CONNECTION | awk '{print $1}')
    HOSTNAME=$(hostname)
    USER=$(whoami)
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    
    echo "SSH Login Alert
    
Server: $HOSTNAME
User: $USER
IP Address: $IP
Time: $TIMESTAMP
    
This is an automated security notification." | mail -s "SSH Login: $USER@$HOSTNAME from $IP" your-email@example.com
fi

The script logic checks for SSH_CONNECTION variable existence, indicating remote login rather than local console access. It extracts client IP address from connection string, captures hostname and username, formats timestamp for readability, then sends formatted email notification containing all relevant session details.

For regular user monitoring, repeat the process editing /home/username/.bashrc files individually. System-wide alert coverage across all users requires creating script in /etc/profile.d/:

sudo nano /etc/profile.d/ssh-alert.sh

Use identical script content but make executable:

sudo chmod +x /etc/profile.d/ssh-alert.sh

Customization options include HTML email formatting for enhanced readability:

echo "<html><body><h2>SSH Login Detected</h2>
<p><strong>Server:</strong> $HOSTNAME</p>
<p><strong>User:</strong> $USER</p>
<p><strong>IP:</strong> $IP</p>
<p><strong>Time:</strong> $TIMESTAMP</p>
</body></html>" | mail -a "Content-type: text/html" -s "SSH Alert: $USER@$HOSTNAME" your-email@example.com

Additional information enrichment includes last login times, system load averages, or active user counts:

LASTLOGIN=$(last -1 $USER | head -1)
LOAD=$(uptime | awk -F'load average:' '{print $2}')

Test configuration by opening new SSH session from different terminal or remote location. Email notification should arrive within seconds to minutes depending on mail delivery latency.

Method 2: Implementing Telegram Notifications

Creating and Configuring Telegram Bot

Telegram bots provide lightweight, real-time notification delivery accessible from mobile devices worldwide. Creating a bot takes minutes through Telegram’s BotFather interface.

Open Telegram application and search for “@BotFather”—the official bot creation tool. Start conversation and use /newbot command. BotFather prompts for bot name (display name shown to users) and username (must end with “bot,” like “MySSHAlertBot”). Upon successful creation, BotFather provides API token—a long string containing numbers and characters.

Critical security note: Treat bot tokens as sensitive credentials equivalent to passwords. Never commit tokens to public repositories or share in unsecured communications.

Create dedicated Telegram group or channel for SSH alerts to separate security notifications from other messages. Add the newly created bot to this group as member.

Obtaining Chat ID requires API interaction. Send message in the group, then retrieve updates via browser or curl:

curl https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates

Response JSON contains chat ID in “chat”:{“id”:-123456789} format. Group IDs typically appear as negative numbers.

Alternative method uses temporary test messages:

curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage" -d "chat_id=<YOUR_CHAT_ID>&text=Test message"

Successful delivery confirms correct bot token and chat ID combination.

Installing Alert Script for Telegram

Telegram notification implementation uses shell script executing upon SSH login. Create script file in /usr/local/bin/ for custom executables:

sudo nano /usr/local/bin/telegram-ssh-alert.sh

Insert complete notification script:

#!/bin/bash

BOT_TOKEN="YOUR_BOT_TOKEN_HERE"
CHAT_ID="YOUR_CHAT_ID_HERE"

if [ -n "$SSH_CONNECTION" ]; then
    IP=$(echo $SSH_CONNECTION | awk '{print $1}')
    HOSTNAME=$(hostname)
    USER=$(whoami)
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    
    MESSAGE=" SSH Login Alert
    
 Server: $HOSTNAME
 User: $USER
 IP: $IP
 Time: $TIMESTAMP"
    
    curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
        -d "chat_id=${CHAT_ID}" \
        -d "text=${MESSAGE}" \
        -d "parse_mode=HTML" > /dev/null 2>&1
fi

Replace YOUR_BOT_TOKEN_HERE and YOUR_CHAT_ID_HERE with actual values obtained during bot creation. Emoji inclusion enhances visual recognition in notification streams. The > /dev/null 2>&1 redirection prevents curl output from appearing in user’s terminal during login.

Make script executable:

sudo chmod +x /usr/local/bin/telegram-ssh-alert.sh

Configure automatic execution via /etc/profile.d/:

sudo nano /etc/profile.d/telegram-notify.sh

Add single line:

/usr/local/bin/telegram-ssh-alert.sh

Make executable:

sudo chmod +x /etc/profile.d/telegram-notify.sh

Alternative PAM integration method provides more reliable triggering. Edit PAM SSH configuration:

sudo nano /etc/pam.d/sshd

Add line after authentication modules:

session optional pam_exec.so seteuid /usr/local/bin/telegram-ssh-alert.sh

PAM method executes scripts regardless of user shell configuration, ensuring consistent notification delivery across all account types.

Test Telegram alerts by initiating new SSH connection. Notification should appear in designated Telegram group within seconds. Debug connection issues by running script manually and observing curl output:

bash -x /usr/local/bin/telegram-ssh-alert.sh

Advanced customization includes HTML formatting for better readability:

MESSAGE="<b>SSH Login Alert</b>

<b>Server:</b> $HOSTNAME
<b>User:</b> $USER
<b>IP:</b> $IP
<b>Time:</b> $TIMESTAMP"

Implement IP geolocation lookup for geographic context:

LOCATION=$(curl -s "https://ipinfo.io/${IP}/json" | grep -o '"city": "[^"]*' | cut -d'"' -f4)

Notification throttling prevents alert spam during maintenance with multiple rapid logins. Track last notification time in temporary file:

THROTTLE_FILE="/tmp/ssh-alert-$USER"
CURRENT_TIME=$(date +%s)
if [ -f "$THROTTLE_FILE" ]; then
    LAST_ALERT=$(cat "$THROTTLE_FILE")
    TIME_DIFF=$((CURRENT_TIME - LAST_ALERT))
    if [ $TIME_DIFF -lt 300 ]; then
        exit 0
    fi
fi
echo "$CURRENT_TIME" > "$THROTTLE_FILE"

This logic suppresses notifications if previous alert occurred within 5 minutes (300 seconds).

Method 3: Slack Integration for Team Notifications

Setting Up Slack Incoming Webhook

Slack webhooks enable posting messages to channels through simple HTTP POST requests. Team collaboration environments benefit from centralized SSH monitoring visible to operations teams.

Access Slack workspace administration panel and navigate to Apps & Integrations section. Search for “Incoming WebHooks” and add to workspace. Select destination channel for notifications—creating dedicated #ssh-alerts or #security-notifications channel maintains organization.

Slack generates unique webhook URL like https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX. Store this URL securely as it grants posting access to the channel.

Customize webhook appearance through Slack interface, setting display name (like “SSH Monitor”), icon, and default posting channel. Test webhook functionality before full implementation:

curl -X POST -H 'Content-type: application/json' \
--data '{"text":"Test SSH alert from Ubuntu 24.04"}' \
https://hooks.slack.com/services/YOUR/WEBHOOK/URL

Message should appear immediately in configured Slack channel.

Creating Slack Notification Script

Slack notifications support rich formatting through attachment structure enabling structured data presentation. Create notification script:

sudo nano /usr/local/bin/slack-ssh-alert.sh

Implement comprehensive alert script:

#!/bin/bash

WEBHOOK_URL="https://hooks.slack.com/services/YOUR/WEBHOOK/URL"

if [ -n "$SSH_CONNECTION" ]; then
    IP=$(echo $SSH_CONNECTION | awk '{print $1}')
    HOSTNAME=$(hostname)
    USER=$(whoami)
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Color coding: green for normal users, danger for root
    if [ "$USER" = "root" ]; then
        COLOR="danger"
        EMOJI=":rotating_light:"
    else
        COLOR="good"
        EMOJI=":key:"
    fi
    
    JSON_PAYLOAD=$(cat <<EOF
{
    "text": "${EMOJI} SSH Login Detected",
    "attachments": [
        {
            "color": "${COLOR}",
            "fields": [
                {
                    "title": "Server",
                    "value": "${HOSTNAME}",
                    "short": true
                },
                {
                    "title": "User",
                    "value": "${USER}",
                    "short": true
                },
                {
                    "title": "IP Address",
                    "value": "${IP}",
                    "short": true
                },
                {
                    "title": "Timestamp",
                    "value": "${TIMESTAMP}",
                    "short": true
                }
            ],
            "footer": "SSH Security Monitor",
            "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png"
        }
    ]
}
EOF
)
    
    curl -s -X POST -H 'Content-type: application/json' \
        --data "$JSON_PAYLOAD" "$WEBHOOK_URL" > /dev/null 2>&1
fi

Color-coded alerts provide instant visual distinction—red/danger alerts for root access warrant immediate attention, while green notifications indicate normal user activity.

Make script executable and configure automatic execution:

sudo chmod +x /usr/local/bin/slack-ssh-alert.sh
sudo nano /etc/profile.d/slack-notify.sh

Add execution line:

/usr/local/bin/slack-ssh-alert.sh

Make profile script executable:

sudo chmod +x /etc/profile.d/slack-notify.sh

Enhanced notifications include additional system context. Capture system load and memory usage:

LOAD=$(uptime | awk -F'load average:' '{print $2}')
MEMORY=$(free -h | awk '/^Mem:/ {print $3 "/" $2}')

Add fields to JSON attachment array for comprehensive monitoring.

IP address filtering excludes trusted networks from generating alerts:

# Trusted IP ranges
if [[ "$IP" =~ ^192\.168\. ]] || [[ "$IP" =~ ^10\. ]]; then
    exit 0
fi

This prevents notification spam from expected internal connections while maintaining alerts for external access attempts.

Test Slack integration by establishing new SSH session. Alert should appear in designated Slack channel with formatted attachment displaying all captured information.

Testing Your SSH Alert Configuration

Comprehensive testing validates alert functionality across different scenarios. Systematic verification ensures reliable notification delivery when actual security events occur.

Testing methodology:

  1. Open new SSH session from different terminal or device
  2. Verify notification receipt within expected timeframe (typically seconds to one minute)
  3. Confirm captured information accuracy—IP address, username, hostname, timestamp
  4. Test multiple user accounts including root and regular users
  5. Verify alerts trigger for both password and key-based authentication
  6. Test from various source IP addresses including local network and external connections

Multiple rapid sequential logins stress-test notification systems and reveal potential delays or failures. Monitor system logs during testing:

sudo tail -f /var/log/auth.log

Correlate SSH authentication events in auth.log with notification delivery timing.

Common testing issues include delayed notifications (mail queue backlog or API latency), missing notifications (script execution failures), duplicate alerts (multiple configuration locations), formatting problems (special characters in notification text). Debug script execution by adding logging:

echo "$(date): SSH alert triggered for $USER from $IP" >> /var/log/ssh-alerts.log

Manual script execution helps isolate configuration problems:

SSH_CONNECTION="203.0.113.5 54321 198.51.100.10 22" bash /usr/local/bin/telegram-ssh-alert.sh

Sets environment variable simulating SSH connection for testing notification generation without actual remote login.

Advanced Configuration and Customization

Alert systems benefit from refinement based on operational requirements and environment-specific needs. Advanced configurations reduce false positives while enriching notification context.

IP Filtering for Trusted Sources

Exclude known safe IP addresses or networks from generating alerts:

TRUSTED_IPS=("203.0.113.5" "198.51.100.0/24" "2001:db8::/32")

for trusted in "${TRUSTED_IPS[@]}"; do
    if [[ "$IP" =~ $trusted ]]; then
        exit 0
    fi
done

Maintains security monitoring while eliminating notification fatigue from routine administrative access.

Severity-Based Alert Routing

Different accounts warrant different alert urgency. Critical notifications for root access route to immediate channels (SMS, phone call) while regular users generate informational alerts:

if [ "$USER" = "root" ]; then
    # Send high-priority alert
    curl -X POST "$CRITICAL_WEBHOOK_URL" --data "$MESSAGE"
else
    # Send standard alert
    curl -X POST "$STANDARD_WEBHOOK_URL" --data "$MESSAGE"
fi

Geographic IP Lookup Integration

Enriching alerts with geographic location data provides threat intelligence context:

GEO_INFO=$(curl -s "https://ipinfo.io/${IP}/json")
CITY=$(echo "$GEO_INFO" | grep -o '"city": "[^"]*' | cut -d'"' -f4)
COUNTRY=$(echo "$GEO_INFO" | grep -o '"country": "[^"]*' | cut -d'"' -f4)
ORG=$(echo "$GEO_INFO" | grep -o '"org": "[^"]*' | cut -d'"' -f4)

MESSAGE="SSH Login from $CITY, $COUNTRY ($ORG)"

Geographic anomalies—logins from unexpected countries—highlight potentially compromised credentials.

Failed Login Attempt Monitoring

Complementing successful login alerts with failed attempt tracking detects ongoing attacks:

# Add to cron job running every 5 minutes
FAILED=$(grep "Failed password" /var/log/auth.log | tail -10)
if [ -n "$FAILED" ]; then
    # Send alert with failed attempt details
fi

Alert Aggregation and Digest Mode

High-activity servers benefit from digest notifications summarizing activity over time periods rather than individual alerts:

# Hourly cron job summarizes SSH activity
LOGINS=$(last -F | grep "$(date '+%Y-%m-%d %H')" | wc -l)
MESSAGE="Hourly SSH Activity Report: $LOGINS logins detected"

Reduces alert volume while maintaining visibility into access patterns.

Multi-Server Centralization

Organizations managing multiple servers aggregate alerts to centralized monitoring:

# Include server identifier in alerts
SERVER_ID="web-prod-01"
MESSAGE="[$SERVER_ID] SSH Login: $USER from $IP"

Enables comprehensive fleet monitoring through single notification channel.

Security Best Practices for SSH and Alert Systems

SSH login alerts represent one component of comprehensive server security requiring layered defense strategies.

Disable Root SSH Login

Preventing direct root access reduces attack surface:

sudo nano /etc/ssh/sshd_config

Set:

PermitRootLogin no

Restart SSH service:

sudo systemctl restart ssh

Enforce sudo elevation for administrative tasks, maintaining audit trail of privileged operations.

Implement Key-Based Authentication

Disable password authentication entirely, requiring cryptographic key pairs:

PasswordAuthentication no
PubkeyAuthentication yes

Key-based authentication eliminates brute-force password attacks while simplifying access management.

Change Default SSH Port

Moving SSH from standard port 22 reduces automated scanning attacks:

Port 2222

Update firewall rules accordingly:

sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp

While not comprehensive security, non-standard ports decrease noise from opportunistic attacks.

Configure Fail2Ban

Install intrusion prevention automatically banning repeat failed login attempts:

sudo apt install fail2ban
sudo systemctl enable fail2ban

Configure SSH jail in /etc/fail2ban/jail.local:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600

Fail2Ban monitors authentication logs and implements temporary IP bans after threshold violations.

Implement UFW Rate Limiting

Ubuntu’s Uncomplicated Firewall provides connection rate limiting:

sudo ufw limit ssh

Restricts connection attempts preventing rapid brute-force campaigns.

Two-Factor Authentication

Google Authenticator PAM module adds second authentication factor:

sudo apt install libpam-google-authenticator

Configure requiring TOTP codes in addition to passwords or keys for enhanced security.

Restrict SSH Access by User/Group

Limit SSH capability to specific accounts:

AllowUsers admin deploy
AllowGroups sshusers

Principle of least privilege reduces available attack surface.

Secure Notification Credentials

Protect bot tokens, webhook URLs, and API keys with restrictive file permissions:

sudo chmod 600 /usr/local/bin/telegram-ssh-alert.sh
sudo chown root:root /usr/local/bin/telegram-ssh-alert.sh

Store sensitive credentials in environment variables or dedicated configuration files separate from script logic.

Regular Security Audits

Periodically review authorized_keys files:

sudo find /home -name authorized_keys -exec ls -la {} \;

Monitor for unauthorized key additions indicating compromised accounts. Keep system packages updated with automatic security patches:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades

Network segmentation using jump boxes for administrative access provides additional security layers. Monitor alert system health ensuring notification delivery doesn’t silently fail—configure “heartbeat” expected alerts detecting monitoring system failures.

Troubleshooting Common Issues

Alert configuration occasionally encounters obstacles requiring systematic debugging.

Email Notifications Not Received

Check Postfix service status:

sudo systemctl status postfix

Examine mail queue for stuck messages:

mailq

Review Postfix logs:

sudo tail -100 /var/log/mail.log

Common issues include DNS resolution failures, SPF/DKIM authentication problems, or ISP blocking outbound SMTP. Check spam folders before assuming delivery failure. Test basic mail functionality separately from SSH alerts:

echo "Test" | mail -s "Test" recipient@example.com

Gmail relay requires app-specific passwords rather than account passwords. Verify credential file configuration and relay host settings.

Telegram Notifications Failing

Validate bot token and chat ID accuracy—common transcription errors cause failures. Test API connectivity directly:

curl -X POST "https://api.telegram.org/bot<TOKEN>/getMe"

Should return bot information. Network firewalls may block outbound HTTPS to Telegram APIs—test with:

curl -v https://api.telegram.org

Script permission problems prevent execution. Verify executable bit:

ls -l /usr/local/bin/telegram-ssh-alert.sh

Should display -rwxr-xr-x. Check curl installation:

which curl

Install if missing:

sudo apt install curl

Add error logging to scripts for debugging:

curl -X POST "..." 2>&1 | tee -a /var/log/telegram-alert-debug.log

Review debug log for API error responses.

Slack Webhook Errors

Verify webhook URL validity—regenerate if necessary through Slack admin panel. Confirm workspace permissions allow webhook posting. Test JSON payload format:

curl -X POST -H 'Content-type: application/json' --data '{"text":"test"}' WEBHOOK_URL

Invalid JSON syntax causes silent failures. Validate JSON structure using online validators before implementing in scripts.

Scripts Not Executing

Confirm .bashrc or profile.d location and sourcing. System-wide scripts require placement in /etc/profile.d/ with executable permissions. Check bash syntax:

bash -n /path/to/script.sh

Reports syntax errors without execution. User-specific alerts only work when modifying correct user’s profile file. Verify script actually runs:

bash -x /etc/profile.d/alert-script.sh

Shows detailed execution trace. Check SSH_CONNECTION variable existence during troubleshooting:

echo $SSH_CONNECTION

Empty output indicates local console rather than SSH session.

Duplicate Notifications

Multiple configuration locations cause duplicate alerts. Search for alert scripts:

sudo grep -r "SSH_CONNECTION" /etc/profile.d/ /home/*/.bashrc /root/.bashrc

Remove redundant configurations retaining single implementation location. PAM configuration combined with profile.d scripts creates duplicates—choose one method.

Permission Denied Errors

Scripts require execute permissions. Set appropriately:

sudo chmod +x /path/to/script.sh

Profile.d scripts need world-readable permissions to execute for all users. Verify file ownership:

ls -l /etc/profile.d/ssh-alert.sh

Should be root:root for system-wide scripts.

Character Encoding Issues

Special characters in notification text cause display problems. Use UTF-8 encoding consistently. Escape quotes and special characters in JSON payloads. Test with simple messages first, then add complexity incrementally.

Maintaining and Monitoring Your Alert System

Alert systems require ongoing maintenance ensuring continued reliability.

Implement quarterly testing schedules verifying notification delivery. Document testing procedures in runbooks accessible to operations teams. Monitor notification success rates—persistent failures indicate configuration problems requiring investigation.

Ubuntu version upgrades occasionally modify SSH configurations or shell initialization behavior. Review alert scripts after major system updates, testing functionality before assuming continued operation. Keep notification service credentials current—rotate API tokens and webhook URLs annually as security best practice.

Back up alert configurations before changes using version control:

git init /etc/ssh-alerts
cp /etc/profile.d/ssh-alert.sh /etc/ssh-alerts/
git add .
git commit -m "SSH alert configuration backup"

Document alert implementation in team wikis or infrastructure-as-code repositories. Include troubleshooting guides, configuration parameters, and escalation procedures.

Implement monitoring for monitoring systems—”dead man’s switch” validation ensures alert infrastructure remains functional. Expected activity patterns (regular administrative access) should generate predictable alerts. Absence of expected notifications indicates system failure requiring investigation.

Analyze accumulated alert data for security intelligence. Review login patterns identifying:

  • Peak activity times for capacity planning
  • Geographic distribution of legitimate access
  • Anomalous login attempts suggesting reconnaissance
  • Compromised credential indicators (multiple failed attempts followed by success)

Tune alert sensitivity based on operational experience. Initial implementations generate false positives requiring refinement. Balance security awareness against alert fatigue—excessive notifications lead to ignored warnings.

Compliance requirements in regulated industries mandate SSH access logging retention. Archive notification records meeting audit requirements. Consider forwarding alerts to SIEM (Security Information and Event Management) platforms for centralized security monitoring and correlation with other infrastructure events.

Scale alert systems as infrastructure grows. Template configurations using configuration management tools (Ansible, Puppet, Chef) enable consistent deployment across server fleets. Centralized notification channels aggregate activity from multiple systems into unified monitoring dashboards.

Congratulations! You have successfully setup SSH Login Alerts. Thanks for using this tutorial to configure SSH Login Alerts on Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the official Ubuntu website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button