Blog

Login/Logout Slack Notifications from an Ubuntu Server

image

Do you want to be notified when someone logs in or out of your server? This step by step guide will tell you exactly how to make it happen!

 

Prerequisites:

-Ubuntu Web server with the latest version of Python installed

-An application that allows one to SSH into a server

-WINSCP (optional)

-A Slack account

-A slack incoming webhook 

Step 1: Login Notification to Slack

  • In your Ubuntu server create a file “login. py”

  • This is the code that you will place in the file:

import sys

import getpass

def send_message_to_slack(text):

  from urllib import request, parse

  import json

  post = {"text": "{0}".format(text)}

  try:

      json_data = json.dumps(post)

      req = request.Request("Your Slack URL goes here",

                            data=json_data.encode('ascii'),

                            headers={'Content-Type': 'application/json'})

      resp = request.urlopen(req)

  except Exception as em:

      print("EXCEPTION: " + str(em))

send_message_to_slack(getpass.getuser() + “ has logged in to the server”)

  • SFTP into your server and go to the /etc/profile.d/  folder

  • Create a .sh file and in the file type “python3 login.py”  (If there is a permissions issue just ssh into the server and add your .sh file there)

  • Now whenever someone logs into your server a message to slack will be sent

 

Step 2: Logout Notification to Slack

  • In your server create a file “logout.py”

  • This is the code that you will place in the file:

import sys

import getpass

def send_message_to_slack(text):

  from urllib import request, parse

  import json

  post = {"text": "{0}".format(text)}

  try:

      json_data = json.dumps(post)

      req = request.Request("Your Slack URL goes here",

                            data=json_data.encode('ascii'),

                            headers={'Content-Type': 'application/json'})

      resp = request.urlopen(req)

  except Exception as em:

      print("EXCEPTION: " + str(em))

send_message_to_slack(getpass.getuser() + " has logged out of the server")
 
  • SFTP into your server and go to the /home/ubuntu/  folder (Note: This step will need to be repeated for each user’s log out that you want to monitor)

  • Make sure that you can view hidden files

  • Open the .bash_logout file and add “python3 logout.py” directly above the existing code (If there is a permissions issue just ssh into the server and edit the .bash_logout file there)

  • Now  when someone logs out of the server a message will be sent to slack