Python 实现批量PING测试基站管理地址

本文介绍了一个使用Python编写的脚本,该脚本能够批量读取IP地址列表并执行ping测试,同时记录测试结果到文件中。脚本还包含创建指定文件夹的功能,确保输出文件的正确存放。

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

import re
import subprocess
import datetime
import time
import os
def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录 # 创建目录操作函数
        os.makedirs(path)
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        return False
def check_alive(ip,count=2,timeout=1):
    #ping网络测试,通过调用ping命令,发送一个icmp包,从结果中通过正则匹配是否有100%关键字,有则表示丢包,无则表示正常
    cmd = 'ping -n %d -w %d %s' % (count,timeout,ip)
    p = subprocess.Popen(cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True
    )
    result = p.stdout.read()
    result=str(result)
    if 'TTL='in result:
        print('可以ping通 :', ip)
        with open('./data/log'+dtime+'.txt', 'a')as rst_file:
                rst_file.write('可以ping通 :' + ip + '\n')
    elif 'TTL expired'in result:
        print('出现环路  :', ip)
        with open('./data/log'+dtime+'.txt', 'a')as rst_file:
                rst_file.write('出现环路 :'+ip+'\n')
    else:
        print('失联  :', ip)
        with open('./data/log'+dtime+'.txt', 'a')as rst_file:
                rst_file.write('失联 :'+ip+'\n')
if __name__ == "__main__":
    dtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    mkpath = "./data"
    mkdir(mkpath)
    path='./ip.txt'
    isExist = os.path.exists(path)
    if not isExist:
        # 如果不存在则添加ip文本
        print('请在当前路径添加 ip.txt !')
        time.sleep(3)
    else:
        # 如果目录存在则批量ping测试
        with open(path,'r') as f:
            with open('./data/log'+dtime+'.txt', 'a')as rst_file:
                rst_file.write('当前查询时间 :' + dtime + '\n')
            for line in f.readlines():
                ip = line.strip()
                check_alive(ip)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值