Skip to content

Instantly share code, notes, and snippets.

@fijimunkii
Created March 28, 2017 22:54
Show Gist options
  • Save fijimunkii/8c88d11371fff141b68743ef96a34025 to your computer and use it in GitHub Desktop.
Save fijimunkii/8c88d11371fff141b68743ef96a34025 to your computer and use it in GitHub Desktop.
announce ssh connections to slack
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 your ssh folder:
sudo nano /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="YOUR_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 -X POST --data-urlencode "payload={\"channel\": \"$channel\", \"mrkdwn\": true, \"username\": \"ssh-bot\", $content, \"icon_emoji\": \":computer:\"}" $url
fi
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
Done
Well that's it. That was easy!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment