Last active
July 26, 2020 18:59
-
-
Save azharisikumbang/ec1fc6db9ba9d51be16d52d75d57eb91 to your computer and use it in GitHub Desktop.
A Simple Python Script for Nagios Telegram Notification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import urllib.request | |
import urllib.parse | |
import base64 | |
import csv | |
import json | |
import os | |
from datetime import datetime | |
CSV_FILE = os.path.join(os.getcwd(), "locations.csv") | |
CHAT_ID = "" | |
TOKEN = "" | |
NAGIOSUSERNAME = "" | |
NAGIOSPASSWORD = "" | |
NAGIOSURL = "" | |
# Set Message | |
def setMessage(message): | |
telegram_params = { | |
'chat_id' : CHAT_ID, | |
'parse_mode' : 'Html', | |
'text' : message | |
} | |
return telegram_params | |
# Notify | |
def notify(message): | |
TELEGRAM_URL = "https://api.telegram.org/bot{0}/sendMessage".format(TOKEN) | |
data = urllib.parse.urlencode(message).encode('ascii') | |
urllib.request.urlopen(TELEGRAM_URL, data) | |
def header(): | |
return setMessage(''' | |
=============================== | |
LAPORAN SITE DOWN | |
{0} | |
=============================== | |
'''.format( | |
datetime.now().strftime('%d/%m/%Y %H:%M:%S %Z') | |
)) | |
def footer(devices, offline): | |
return setMessage(''' | |
=============================== | |
Total Site : {0} | |
Total Online : {1} | |
Total Offline : {2} | |
=============================== | |
'''.format( | |
devices, | |
devices - offline, | |
offline | |
)) | |
def main(): | |
notify(header()) | |
# Get Data | |
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() | |
password_mgr.add_password(None, NAGIOSURL, NAGIOSUSERNAME, NAGIOSPASSWORD) | |
handler = urllib.request.HTTPBasicAuthHandler(password_mgr) | |
opener = urllib.request.build_opener(handler) | |
u = opener.open(NAGIOSURL) | |
jsonData = json.loads(u.read().decode("utf-8")) | |
devices = 0 | |
devices_offline = 0 | |
with open(CSV_FILE) as csv_file: | |
csv_reader = csv.reader(csv_file, delimiter=',') | |
for csv_row in csv_reader: | |
devices+=1 | |
if jsonData['data']['hostlist'][csv_row[0]]['status'] != 2: | |
devices_offline+=1 | |
lastonline = jsonData['data']['hostlist'][csv_row[0]]['last_time_up'] | |
lastonline = datetime.fromtimestamp(lastonline/1000.0) | |
text = ''' | |
{0} | |
Ip : {1} | |
Terakhir Online : {2}'''.format( | |
csv_row[0], | |
csv_row[1], | |
lastonline.strftime('%d/%m/%Y %H:%M:%S %Z'), | |
) | |
notify(setMessage(text)) | |
notify(footer(devices, devices_offline)) | |
# run | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment