python下使用ping检查网络连通情况

本文介绍如何利用Python调用ping命令,监测网络连通情况,并将结果记录到日志文件。读者需要准备一个包含目标地址的webs.txt文件,并创建一个名为log的文件夹来保存日志。同时,文章还提及了Python中time模块的strftime函数及其时间日期格式化符号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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的文件夹。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值