python下使用ping檢查網絡連通情況

使用python調用ping命令,然後在日誌中記錄ping的結果,用來監測網絡連通情況。

代碼:

from time import *
from subprocess import *


webf= open("webs.txt","r")
webs=[]
for w in webf:
    webs.append(w.strip())

def logAppend(log,info):
    inttime = time()
    structtime = localtime(inttime)
    strtime = strftime("%Y-%m-%d,%H:%M:%S",structtime)
    print "at ",strtime

    log.write("==================  "+strtime+"  ==================\n")
    log.write(info)
    log.write("\n\n")
    print "append info to file :",log.name
    print info


def netCheck():
    while True:
        for url in webs:
            p = Popen(["ping.exe",url],
                      stdin=PIPE,stdout=PIPE,stderr=PIPE,
                      shell=True)
            out = p.stdout.read()
            log = open("log\\"+url+".log","a")

            logAppend(log,out)
            log.close()
            sleep(0.01)
        print "waiting ..."
        sleep(60*15) #sleep for 15min. 60*15
    return

def main():
    """
    the main function
    """
    print "start..."
    netCheck()
    print "end."


if __name__ == "__main__":
    main()

說明:

webs.txt爲目的地址,如www.baidu.com,每行一個。

需要在當前目錄下自己建立一個名爲log的文件夾。

關於time模塊:

inttime = time()##得到的是當前時間的小數形式:1366356992.617
structtime = localtime(inttime)###轉換爲本地時間,
#返回的結果是:time.struct_time(tm_year=2013, tm_mon=4, tm_mday=19, 
tm_hour=15, tm_min=36, tm_sec=32, tm_wday=4, tm_yday=109, tm_isdst=0)
#這個看着很不順眼,繼續格式化轉換:
strtime = strftime("%Y-%m-%d,%H:%M:%S",structtime)
##返回的就是你想要的格式的字符串:2013-04-19,15:36:32


其他參數類型:

strftime(format[, tuple]) -> string
將指定的struct_time(默認爲當前時間),根據指定的格式化字符串輸出
python中時間日期格式化符號:
%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12) 
%M 分鐘數(00=59)
%S 秒(00-59)

%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天爲星期的開始
%w 星期(0-6),星期天爲星期的開始
%W 一年中的星期數(00-53)星期一爲星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章