Skip to content

Instantly share code, notes, and snippets.

@GregNing
Last active December 17, 2024 07:50
Show Gist options
  • Save GregNing/869ca29483b60a70040d3fdd7c3fd674 to your computer and use it in GitHub Desktop.
Save GregNing/869ca29483b60a70040d3fdd7c3fd674 to your computer and use it in GitHub Desktop.
ssh to ec2 and send notification to slack
  1. you need to create app https://api.slack.com/apps/new
  2. enable webhook on your app https://api.slack.com/apps/xxxxxxx/incoming-webhooks?
  3. checkout your webhook url and copy https://hooks.slack.com/services/xxxxxx/xxxxx/xxxxx
  4. your SLACK_WEBHOOK_URL is https://hooks.slack.com/services/xxxxxx/xxxxx/xxxxx
  5. create ssh-bot channel
  6. Add ssh script file sudo vim /etc/ssh/scripts/notify.sh
#!/bin/sh

url="SLACK_WEBHOOK_URL"

if [ "$PAM_TYPE" != "close_session" ]; then
  channel="#ssh-bot"
  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\": \":ghost:\"}" $url
fi  
  1. Give script permission
  sudo chmod +x /etc/ssh/scripts/notify.sh
  1. Add script to pam.d
  sudo echo "session optional pam_exec.so seteuid /etc/ssh/scripts/notify.sh" >> /etc/pam.d/sshd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment