Added remote notify for icinga sms

This commit is contained in:
Pavel Valach 2022-07-08 11:42:52 +02:00
parent 334336f004
commit 052d95bbe2
2 changed files with 90 additions and 0 deletions

54
icinga_service_notify.py Executable file
View File

@ -0,0 +1,54 @@
#!/usr/bin/python3
import logging
import os
from pydbus import SystemBus
from gi.repository import GLib
from datetime import datetime
import sms_functions
def assemble_sms():
since_date = datetime.fromtimestamp(int(os.environ.get('LONGDATETIME')))
str_list = []
str_list.append("Icinga {}\n".format(os.environ.get('NOTIFICATIONTYPE')))
str_list.append("{} [{}] is {}\n".format(os.environ.get('SERVICEDESC'), os.environ.get('HOSTALIAS'), os.environ.get('SERVICESTATE')))
str_list.append("at {}\n".format(since_date.strftime('%Y-%m-%dT%H:%M:%S')))
str_list.append("Comment: [{}] {}".format(os.environ.get('NOTIFICATIONAUTHORNAME'), os.environ.get('NOTIFICATIONCOMMENT')))
return ''.join(str_list)
def main():
# Setup logging
logfile = "/opt/sms/sms.log"
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT,filename=logfile,level=10)
logger = logging.getLogger('icingasms')
# check param
smsrcpt = os.environ.get('USERMOBILE')
if not smsrcpt:
logger.error('No SMS number given')
raise Exception('No SMS number given for message')
# Assemble SMS
smsstring = assemble_sms()
logger.info("Sending SMS: %s", smsstring)
success = False
retries = 0
max_retries = 3
while not success and retries < max_retries:
retries += 1
try:
# Contact ModemManager, unlock SIM and send SMS to emergency numbers
sms_functions.send_sms([ smsrcpt ], smsstring)
except sms_functions.SIMError as err:
logger.exception('SIM Error when sending SMS')
except sms_functions.ModemManagerError as err:
logger.error('Error when sending SMS: {0}'.format(e.value))
else:
success = True
if __name__ == "__main__":
main()

36
icinga_service_notify_remote.py Executable file
View File

@ -0,0 +1,36 @@
#!/usr/bin/python3
import logging
import os
import sys
import subprocess
import shlex
from icinga_service_notify import assemble_sms
import sms_functions
def main():
sms_msg = assemble_sms()
sms_number = os.environ.get('USERMOBILE')
# logger.info("Remote - Sending SMS to %s: %s", sms_number, sms_msg)
hostname = sys.argv[1]
success = False
retries = 0
max_retries = 3
while not success and retries < max_retries:
retries += 1
try:
# Escape message and number for remote shell
sms_msg = shlex.quote(sms_msg)
sms_number = shlex.quote(sms_number)
# Contact remote host
subprocess.run([ '/usr/bin/ssh', hostname, '/opt/sms/send_sms.py', sms_msg, sms_number ], check=True)
except:
raise
else:
success = True
if __name__ == "__main__":
main()