Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Last active December 2, 2021 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaibhavpandeyvpz/5d27b3e8d0591e76ebb1339ae68cd517 to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/5d27b3e8d0591e76ebb1339ae68cd517 to your computer and use it in GitHub Desktop.
Send SSH login notifications to Slack

Setting up notifications for successful SSH logins to Slack on a Linux server is pretty easy. Before everything, please make sure to create a Slack app (if not already), add a Webhook and keep its URL handy.

To get started, login to your instance as root (or as a sudoer user) and run below commands:

# create a directory in /opt
sudo mkdir -p /opt/ssh2slack

# paste the contents from file included and save it with Ctrl+O and Ctrl+X
sudo nano /opt/ssh2slack/slack_message.json

# paste the contents from file included and save it with Ctrl+O and Ctrl+X
sudo nano /opt/ssh2slack/slack_send.sh
sudo chmod +x /opt/ssh2slack/slack_send.sh

Now open SSH config in a text editor using following command:

sudo nano /etc/ssh/sshd_config

Paste the below line at the bottom and save the file with Ctrl+O and Ctrl+X:

ForceCommand "/opt/ssh2slack/slack_send.sh"

Finally restart the SSH server using below command:

sudo systemctl restart sshd

You should now start receiving login notifications in Slack from next time onwards.

{
"text": "Someone :eyes: logged in :unlock: over _SSH_ to *$HOST*.",
"attachments": [
{
"mrkdwn_in": [
"text"
],
"text": "Session details are as below:",
"fields": [
{
"title": "User",
"value": "$USER",
"short": true
},
{
"title": "IP address",
"value": "<https://ipapi.co/$IP|$IP>",
"short": true
}
],
"color": "#f35a00"
}
]
}
#!/bin/bash
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
WEBHOOK_URL=https://hooks.slack.com/services/<your-webhook-url>
SSH_CLIENT_STR=($SSH_CLIENT)
IP=${SSH_CLIENT_STR[0]}
HOST=$(hostname)
MESSAGE_ORIGINAL=$(< "$SCRIPT_DIR/slack_message.json")
MESSAGE_REPLACED=$(echo "$MESSAGE_ORIGINAL" | sed -e "s/\$HOST/$HOST/g;s/\$IP/$IP/g;s/\$USER/$USER/g;")
curl --silent --output /dev/null \
-X POST \
-H 'Content-type: application/json' \
--data "$MESSAGE_REPLACED" \
$WEBHOOK_URL
bash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment