mindau
4/27/2017 - 4:39 PM

send notifications from Linux fail2ban, ssh auth and others actions to Slack

send notifications from Linux fail2ban, ssh auth and others actions to Slack

#!/bin/sh

# Display usage information
function show_usage {
  echo "Default Usage: $0 [subject] [action] [msg]"
  echo "Example: $0 DATABASE backup succefully"
  echo "Custom actions: $0 fail2brain start|stop|ban (ip)|unban (ip)"
  echo "Custom actions: $0 sshauth (use variables from pam_exec to generate msg)."
  exit
}

# Check for script arguments
if [ $# -lt 1 ]
then
  show_usage
fi

# Custom reporting
if [ "$1" = 'fail2ban' ]
then
	#slack.conf start and stop not set
	if [ "$2" = 'start' ]
	then
	  message='Fail2ban just started.'
	  echo $message | path/to/slackpost.sh
	elif [ "$2" = 'stop' ]
	then
	  message='Fail2ban just stopped.'
	  echo $message | path/to/slackpost.sh
	elif [ "$2" = 'ban' ]
	then
	  message=$([ "$2" != '' ] && echo "[$1] just banned $3" || echo 'Fail2ban just banned an ip.' )
	  echo $message | path/to/slackpost.sh
	elif [ "$2" = 'unban' ]
	then
	  message=$([ "$2" != '' ] && echo "[$1] just unbanned $3" || echo "Fail2ban just unbanned an ip." )
	  echo $message | path/to/slackpost.sh
	else
	  show_usage
	fi
# Extra check if not logout (close_session)
elif [ "$1" = "sshauth" ]
then
	#slack.conf start and stop not set
	if [ "$PAM_TYPE" != "close_session" ]
	then
	  #env is last cmd variables
	  #subject="SSH Login: $PAM_USER from $PAM_RHOST on $host"
	  # Message to send, e.g. the current environment variables.
	  message="$PAM_RHOST has just connected on $HOSTNAME with user $PAM_USER (PAM_TYPE=$PAM_TYPE)"
    	  # message="`env`"
	  echo $message | path/to/slackpost.sh
 	fi

# Default 
else
	echo "[$1] action: $2 msg: $3" | path/to/slackpost.sh
fi