Skip to content

Instantly share code, notes, and snippets.

@lennax
Created July 29, 2015 19:43
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 lennax/505327d0fd3ebde0aee9 to your computer and use it in GitHub Desktop.
Save lennax/505327d0fd3ebde0aee9 to your computer and use it in GitHub Desktop.
call process and send unicode mail with status
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2015 Lenna X. Peterson
# All rights reserved
import os
import socket
import subprocess
import sys
# # # # # # # # # # # # # # # #
# FILL THESE OUT
sender_name = "admin"
recipient_address = ""
# # # # # # # # # # # # # # # #
def send_mail(subject, message, recipient_address,
sender_address=None, sender_name=None):
"""
Send unicode mail.
"""
if sender_address is None:
sender_address = "{user}@{fqdn}".format(
user=os.environ['LOGNAME'],
fqdn=socket.getfqdn())
if sender_name is None:
sender_name = os.environ['LOGNAME']
os.environ['LANG'] = "en_US.utf8"
os.environ['LC_CTYPE'] = "en_US.utf8"
mail_fmt = """Subject: {subject}
From: {sender_name} <{sender_address}>
To: {recipient_address}
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
{message}"""
mail = mail_fmt.format(subject=subject,
sender_address=sender_address,
sender_name=sender_name,
recipient_address=recipient_address,
message=message)
sendmail_cmd = ["/usr/sbin/sendmail", "-i", "-f", sender_address, "-F",
sender_name, recipient_address]
mailproc = subprocess.Popen(sendmail_cmd, stdin=subprocess.PIPE)
mailproc.communicate(mail.encode("utf-8"))
def main():
"""Run command and send status"""
# Configure mail
message_kwargs = dict(user=os.environ['LOGNAME'],
hostname=socket.gethostname())
# Prepare command
args = sys.argv[1:]
if not args:
print("Usage: mailstatus.py [script to watch]")
sys.exit(1)
partialargs = args[:20]
if len(partialargs) < len(args):
partialargs.append("...")
# Run process
proc = subprocess.Popen(args)
proc.communicate()
pid = proc.pid
exitcode = proc.returncode
smiley = "☺"
frowny = "😞"
teethgrin = "😀"
grin = "😃"
sadcry = "😭"
# Format message
if exitcode:
status = sadcry
else:
status = grin
subject = '"{hostname} {pid} {status}"'.format(pid=pid, status=status,
**message_kwargs)
message_kwargs['cmd'] = " ".join(partialargs)
message_kwargs['exitcode'] = exitcode
message = "{status}\n'{cmd}' exited {exitcode}\n{user}@{hostname}".format(status=status, **message_kwargs)
send_mail(subject=subject,
message=message,
recipient_address=recipient_address,
sender_name=sender_name)
sys.exit(exitcode)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment