Skip to content

Instantly share code, notes, and snippets.

@5t111111
Created September 15, 2013 16:01
Show Gist options
  • Save 5t111111/6572003 to your computer and use it in GitHub Desktop.
Save 5t111111/6572003 to your computer and use it in GitHub Desktop.
Send alert-email via Gmail when FreeNAS ZPool fails.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import socket
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
# =====================================
# CONFIG
TEST = False
# Email settings
FROM = 'ENTER FROM-ADDRESS' # e.g. root@freenas.local
TO = 'ENTER TO-ADDRESS' # e.g. youename@gmail.com
# Gmail SMTP settings
LOGIN = 'ENTER GMAIL LOGIN ID' # e.g. yourname@gmail.com
PASSWORD = 'ENTER GMAIL LOGING PASSWORD '
# Change the following list of the disks
DISKS = [
'/dev/ada0',
'/dev/ada1',
'/dev/ada2',
'/dev/ada3',
]
# Usually you don't need to change the following settings
ZPOOLCMD = '/sbin/zpool'
SMARTCMD = '/usr/local/sbin/smartctl'
ZPOOL_FINEMSG = "all pools are healthy"
SMART_FINEMSG = "SMART overall-health self-assessment test result: PASSED"
class Gmailer(object):
_message = None
def __init__(self, from_addr, to_addr, subject, body, encoding):
msg = MIMEText(body, 'plain', encoding)
msg['Subject'] = Header(subject, encoding)
msg['From'] = from_addr
msg['To'] = to_addr
msg['Date'] = formatdate()
self._message = msg
def send_email(self, login, password):
try:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(login, password)
s.sendmail(self._message['From'], [self._message['To']], self._message.as_string())
s.close()
except Exception, e:
print e
sys.exit(1)
# execute a command and return its output
def run_command(c):
try:
proc = os.popen(c)
out = proc.read().strip()
return out
except Exception, e:
print e
sys.exit(1)
# create a summary-text of failed-command's output and additional details
def create_summary(failed, details):
s = failed
s += "\n----------\n\n"
s += details
return s
def main():
hostname = socket.gethostname()
# Zpool Status checking
zpool_status_x = run_command(ZPOOLCMD + " status -x")
if TEST or zpool_status_x.find(ZPOOL_FINEMSG) == -1:
zpool_status = run_command(ZPOOLCMD + " status")
text = create_summary(zpool_status_x, zpool_status)
subject = ' '.join(['[FreeNAS]', hostname, 'ZPool Status'])
mailer = Gmailer(FROM, TO, subject, text, 'utf-8')
mailer.send_email(LOGIN, PASSWORD)
# SMART checking
for disk in DISKS:
smart_health = run_command(SMARTCMD + ' --health ' + disk)
if TEST or smart_health.find(SMART_FINEMSG) == -1:
smart = run_command((SMARTCMD + ' --all ' + disk))
text = create_summary(smart_health, smart)
subject = ' '.join(['[FreeNAS]', hostname, 'S.M.A.R.T.', disk])
mailer = Gmailer(FROM, TO, subject, text, 'utf-8')
mailer.send_email(LOGIN, PASSWORD)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment