#!/usr/bin/python

"""
  Lezione numero 7
"""

import os,re

hostList = [ '127.0.0.1', 'www.eulogika.net', 'xxx.yyy.zzz' ]
mailTo = 'info@localhost'

pingRegex = r'.*(?P<trans>\d+)\s+packets transmitted.*\s+' + \
  r'(?P<recv>\d+)\s+packets received.*\s+' + \
  r'(?P<loss>\d+)% packet loss'

for host in hostList:
  ping = os.popen('ping -c 3 -i 1 ' + host + ' 2>&1')
  data = ping.read()

  match = re.match(pingRegex, data, re.DOTALL)
  if match:
    print '%s:\t%s transmitted, %s received, %s%% lost' % ( host,match.group('trans'), match.group('recv'), match.group('loss') )
    if match.group('loss') != '0':
      os.system('mail -s \'Ping failure: %s\' %s </dev/null >/dev/null' % ( host, mailTo ))
    else:
      print host + ':\tPING ERROR' os.system('mail -s \'Ping ERROR: %s\' %s </dev/null >/dev/null' % ( host, mailTo ))