Login/Logout Slack Notifications from an Ubuntu Server

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

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”)

Step 2: Logout Notification to Slack

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")
 

Hello

Summer Intern