Skip to content

Instantly share code, notes, and snippets.

@chris-x86-64
Created April 13, 2016 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-x86-64/3b3498fec516060af842ba0477649e14 to your computer and use it in GitHub Desktop.
Save chris-x86-64/3b3498fec516060af842ba0477649e14 to your computer and use it in GitHub Desktop.
A Python script which posts login alerts to Slack webhook. (Requires 'who' command)
import socket
import commands
import urllib
import urllib2 as urlrequest
import json
from datetime import datetime
SLACK_POST_URL = "https://hooks.slack.com/services/[TOKEN]"
def build_attachment():
post_json = {
"attachments": [
{
"fallback": "Shell Login Detected",
"color": "warning",
"pretext": "ALERT - Shell Access on %s" % datetime.now().isoformat(),
"fields": [
{
"title": "Hostname",
"value": socket.gethostname(),
"short": "false"
},
{
"title": "Users logged in",
"value": commands.getoutput('who'),
"short": "false"
}
]
}
]
}
return post_json
def post(payload):
payload_json = json.dumps(payload)
data = urllib.urlencode({"payload": payload_json})
req = urlrequest.Request(SLACK_POST_URL)
response = urlrequest.build_opener(urlrequest.HTTPHandler()).open(req, data.encode('utf-8')).read()
return response.decode('utf-8')
post(build_attachment())
# Put this script in /etc/profile.d/
/usr/bin/python /path/to/script.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment