# author xinwang
# -*- coding: GB2312 -*-
import subprocess
import re
import smtplib
from email.mime.text import MIMEText

class LinkState(object):

  def __init__(self,ip):
    self.ip = ip
    self.getLinkState(self.ip)

  def getLinkState(self,ip):
    p = subprocess.Popen(["ping.exe", ip],
    stdin = subprocess.PIPE,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
    shell = True)

    out = p.stdout.read().decode('gb2312')
    # print(out)

    s='无法访问目标主机'
    s2='100% 丢失'

    reg=re.compile(s)
    reg2=re.compile(s2)
    r=reg.findall(out)
    r2=reg2.findall(out)
    # print(r)
    if len(r)==4 or r2:
      #print('dead')
      self.send_mail('dead',self.ip+' is dead')

  def send_mail(self, sub, content):
    to_list = ['yonghuixia@zmtel.com', 'wangxingg@126.com']
    mail_host = "smtp.163.com"
    mail_user = "xxwf0903"
    mail_pass = "wxin20168"
    mail_postfix = "163.com"

    me = "hello" + "<" + mail_user + "@" + mail_postfix + ">"
    msg = MIMEText(content, _subtype='plain', _charset='gb2312')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
  try:
    server = smtplib.SMTP()
    server.connect(mail_host)
    server.login(mail_user, mail_pass)
    server.sendmail(me, to_list, msg.as_string())
    server.close()
    return True
  except Exception as e:
    print(str(e))
    return False

if __name__ == '__main__':
ip = '172.16.34.30'
LinkState(ip)