exec-notify/execNotify

66 lines
1.5 KiB
Python
Executable File

#!/usr/bin/env python3
from sys import argv
import socket
from typing import List
from execNotifyDir import exec, config, mail
def main():
prevMailError = checkPrevError()
if len(argv) >= 2:
success = executeCommand(argv[1:])
else:
success = True
if prevMailError:
tryToInform()
if not success:
exit(1)
else:
exit(0)
def executeCommand(command: List) -> bool:
keys = ['command', 'status', 'stderr', 'stdout']
code, stdout, stderr = exec.execute(command)
values = [str(command), str(code), stderr, stdout]
BODY = ''
for key, value in zip(keys, values):
BODY += '=== {} ===\n{}\n'.format(key, value)
print(BODY)
if code != 0:
hostname = socket.gethostname()
SUBJECT = '{} | {}'.format(hostname, str(command))
mail.sendMailOrWriteToFile(SUBJECT=SUBJECT, BODY=BODY)
return False
else:
return True
def checkPrevError():
return config.getErrorFile().exists()
def tryToInform():
"""
Try to inform user via mail about previous error(s) that could not be sent to him before.
Maybe this time sending of an email works ;)
"""
SUBJECT = '{} | Some mails not sent!'.format(socket.gethostname())
BODY = 'Please check the file {} for mails which could previously not be sent to you!\n' \
'Note: You may delete the file after reading it ;)'.format(
config.getErrorFile())
mail.sendMail(SUBJECT=SUBJECT, BODY=BODY)
if __name__ == '__main__':
main()