home

How to get Discord messages on SSH logins

This will walk through how to send messages on Discord when a new SSH login occurs on one of your machines. Using Discord webhooks and rsyslog’s omprog we will watch system logs and send a message when appropriate.

If you have a syslogs server running this on it will cause all logins from machines it is monitoring to result in messages. If you do not have a syslogs server and would like to have one see this writeup.

There are two parts to this setup process:

  1. Adding a webhook to your Discord server.
  2. Sending messages to that webhook based on syslogs.

Adding a discord webhook

To add a webhook open the Discord application, go to the settings for your server, and go to the integrations tab. Open the webhooks integrations page and press new webhook. From here you can name your bot and give it a profile photo if you would like.

Once you are ready press the “Copy Webhook URL” button and place it somewhere you’ll be able to locate it again.

Sending messages to the webhook based on syslogs

On your syslogs server or the server that you would like to send notifications from create a script called notify.sh and give it executable permissions.

touch notify.sh
chmod +x notify.sh

Then, place the following script inside of it where <URL> is replaced with the Discord webhook URL that you got in the last step.

#!/bin/bash

URL="<URL>"

while read line
do
    if [[ "$line" == *"pam_unix(sshd:session): session opened for user"* ]]; then
    curl \
        -X POST \
        -H "Content-Type: application/json" \
        -d '{"content":"'"🚨 \`${line}\`"'"}' \
        $URL
    fi
done

At this point you can test that your script works by piping some previous logs into the script as follows:

tail -200 /var/log/auth.log | ./notify.sh

If you have recently accessed your server you ought to see a message sent where you configured the webhook.

Having verified that your webhook is working edit /etc/rsyslog.conf by adding the following lines:

module(load="omprog")
action(type="omprog" binary="/home/admin/notify.sh")

These will enable the omprog module which sends incoming syslogs via standard input to your notify.sh executable. Note that if you created your notify.sh script somewhere other than /home/admin/ you will need to use a different path to the script.

Having done that you are now done. Nice.