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:

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/

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

 if [ "$PAM_TYPE" != "close_session" ]; then
  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/

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

session optional seteuid /etc/ssh/

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

Well that’s it. That was easy!

Share this post

Post Comment