程式紀錄~使用python測試閘道端點

8 views
Skip to first unread message

win...@nyps.kh.edu.tw

unread,
Nov 14, 2018, 7:35:31 PM11/14/18
to windf...@googlegroups.com
# -*- coding: utf-8 -*-
'''
這支程式使用multi方式,
可用來ping學校Gateway是否OK,偵測失敗的網頁會寄信通知!
在個人PC執行時間:45秒
設計:Windfly
日期:2015-09-01
程式語言:Python2.7
'''
import os
import gevent
import smtplib
from gevent import monkey
from datetime import datetime
from email.mime.text import MIMEText
monkey.patch_all()
from datetime import datetime

SCHOOL_IP = [
            ['馬公國小','140.127.235.xxx'], ['文澳國小','140.127.236.xxx'], ['西嶼國中','140.127.236.xxx']
            ]


def check_ping(hostname):
	

    #response = os.system("ping -c 2 " + hostname) Centos執行的話     
    response = os.system("ping -n 1 " + hostname[1])
    if response != 0:
    	sendmail(hostname[0])
        return hostname[0].decode('utf-8').encode('big5') + "學校閘道斷線".decode('utf-8').encode('big5')

def sendmail(hostname):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    SEND_USER = 'xxx...@gmail.com'
    SEND_PSWD = 'xxxxxxx'
    SEND_TO = [SEND_USER, 'xxx...@mail.phc.edu.tw']
    content = """這是學校閘道斷線的mail通知信。"""
    text_subtype = 'plain'
    MSG = MIMEText(content, text_subtype)
    MSG['Subject'] = hostname + "--- 學校閘道偵測失敗。" 
    MSG['From']    = 'xxx...@gmail.com'

    try:
        server.login(SEND_USER, SEND_PSWD)
        server.sendmail(SEND_USER, SEND_TO, MSG.as_string())
    except Exception as ex:
        return "error" + "%s" % ex

    server.quit()



t1 = datetime.now() #開始時間
jobs = [gevent.spawn(check_ping, each) for each in SCHOOL_IP]
gevent.joinall(jobs)


i = 0
for x in jobs:
    if jobs[i].value:
        print jobs[i].value
    i += 1


total = datetime.now() - t1 #花費時間

print '%s: %s' % ('花費時間 '.decode('utf-8').encode('big5'), total)
Reply all
Reply to author
Forward
0 new messages