How to get Slack notifications for SSH sessions

By February 10, 2015How-to, Software Development

I wanted to write a quick how-to based on something I discovered today that I think others my find useful.

I decided we should be monitoring SSH connections to our production server to make sure nothing unexpected is going on now that we’re getting some real visibility. Obviously Slack is awesome and therefore the place to put it, so I came up with a little set of scripts to make it happen:

1. Add the incoming webhook

First, [add a new incoming webhook integration to Slack]( This will open a URL we can use to push a notification into a Slack channel. Keep this URL somewhere as you’ll need it later…

2. Update your SSH server configuration

Secondly we need SSH to force a script execution on login which we can do by adding an option to our SSH server configuration file. You can probably find yours at “`/etc/ssh/sshd_config“`.

Add this line to your configuration file:

ForceCommand /home/ubuntu/ssh-wrapper

(modify the path in a way that suits you)

3. Create a script that talks to Slack
Here is the ssh-wrapper script I used.

Essentially it reads the user’s IP address and POSTs it along with a message to the Slack webhook we created earlier. You’ll have to put in your webhook address in place of YOUR_SLACK_WEBHOOK_ADDRESS (duh!):

 #! /bin/bash

# Find the session's remote IP address
 ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

# Tell Slack we logged in!
 {"text":"Somebody connected to your server via ssh from '"$ip"'",
 "username":"SSH Monitor",

# Allow the session to run:

# Tell Slack we're logging out!
 {"text":"Somebody disconnected from '"$ip"'",
 "username":"SSH Monitor",

4. Profit

Now when somebody logs in or out you should get a handy-dandy notification in your channel that looks something like this (depending on your username/text):
Awesome Slack notification

Leave a Reply