Post successful SSH logins to Slack channel

I use Slack for many things and it’s great to see so many integrations are available out of the box. But building integrations yourself is extremely easy using its Incoming Web Hooks.

Wouldn’t it be nice if you could see a message in Slack each time a user connects to one of your machines over SSH? Yes it would.

Slack Setup

So first you would need to configure an Incoming Web Hook in Slack:

https://YOUR_DOMAIN.slack.com/apps/manage/custom-integrations

Configuring this will give you a Webhook URL to which you can post your messages.

Machine Setup

Now connect to your machine and create a script in the ssh folder:

sudo vim /etc/ssh/notify.sh

Add the following code to the script which we’ll configure to run each time a user signs in:

#!/bin/sh
 if [ "$PAM_TYPE" != "close_session" ]; then
  url="SLACK_WEBHOOK_URL"
  channel="#ssh-logins"
  host="`hostname`"
  content="\"attachments\": [ { \"mrkdwn_in\": [\"text\", \"fallback\"], \"fallback\": \"SSH login: $PAM_USER connected to \`$host\`\", \"text\": \"SSH login to \`$host\`\", \"fields\": [ { \"title\": \"User\", \"value\": \"$PAM_USER\", \"short\": true }, { \"title\": \"IP Address\", \"value\": \"$PAM_RHOST\", \"short\": true } ], \"color\": \"#F35A00\" } ]"
  curl --connect-timeout 5 -X POST --data-urlencode "payload={\"channel\": \"$channel\", \"mrkdwn\": true, \"username\": \"ssh-bot\", $content, \"icon_emoji\": \":computer:\"}" $url
 fi &>/dev/null &

Now make the script executable:
sudo chmod +x /etc/ssh/notify.sh

Finally add the following line to /etc/pam.d/sshd:

session optional pam_exec.so seteuid /etc/ssh/notify.sh

Now every time when someone login the server, you’d get msg in slack as below,


Well that’s it. That was easy!

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *