Skip to content

Instantly share code, notes, and snippets.

@agungsijawir
Created November 3, 2019 13:01
Show Gist options
  • Save agungsijawir/dd2a0ce2d7b4976b95524cb8b51732f5 to your computer and use it in GitHub Desktop.
Save agungsijawir/dd2a0ce2d7b4976b95524cb8b51732f5 to your computer and use it in GitHub Desktop.
Allow sending message to telegram bot when someone access shell

Shell Script that sends alerts to Telegram Bot

  1. Create your bot with help from BotFather. Make sure it has inline_mode enabled.

  2. Create shell script on /etc/pam.d directory named ssh_access.sh.

    touch /etc/pam.d/ssh_access.sh chmod 0700 /etc/pam.d/ssh_access.sh chown root:root /etc/pam.d/ssh_access.sh

  3. Put script below to ssh_access.sh

#!/bin/sh

TELEGRAM_BOT_ID=123456789
TELEGRAM_BOT_KEY=123456

BODY="
A SSH login was successful, so here are some information for security:
  	User:        $PAM_USER
	User IP Host: $PAM_RHOST
	Service:     $PAM_SERVICE
	TTY:         $PAM_TTY
	Date:        `date`
	Server:      `uname -a`
"

if [ ${PAM_TYPE} = "open_session" ]
then
   curl -X POST \
	   -H 'Content-Type: application/json' \
	   -d "{\"chat_id\": ${TELEGRAM_BOT_ID}, \"text\": \" ${BODY} \"}" \
	   https://api.telegram.org/bot${TELEGRAM_BOT_KEY}/sendMessage
fi

exit 0
  1. Add a line at the end of /etc/pam.d/sshd
# SSH Alert script
session required pam_exec.so /etc/pam.d/ssh_access.sh
@agungsijawir
Copy link
Author

tested on Debian 9 (stretch)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment