Python实现自动检测设备连通性并发送告警到企业微信

背景:门禁机器使用的WiFi连接,因为某些原因会不定期自动断开连接,需要人工及时干预,以免影响门禁数据同步,故写此脚本,定时检测门禁网络联通性。

bash 复制代码
#首次使用要安装tcping模块
pip install tcping
bash 复制代码
from tcping import Ping
import csv
from datetime import datetime
import requests, json

def SendWeiXinWork(user,context):
    corpid='填企业ID' #企业ID
    appsecret='填secret'  #secret
    agentid=填AgentID  #AgentID
    #获取accesstoken
    token_url='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + appsecret
    req=requests.get(token_url)
    accesstoken=req.json()['access_token']
    #发送消息
    msgsend_url='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken
    touser=user
    params={
            "touser": touser,
    #       "toparty": toparty,
            "msgtype": "text",
            "agentid": agentid,
            "text": {
                    "content": context
            },
            "safe":0
    }
    req=requests.post(msgsend_url, data=json.dumps(params))
 

 
def pingip(ipAddress,request_nums):
    """
    ping ip
    :param ipAddress:
    :param request_nums: 请求次数
    :return: 丢包率loss和统计结果res
    """
    ping = Ping(ipAddress,3718,3)#3718是端口号,我的门禁机器只有这个端口号可以ping通
    ping.ping(request_nums)
    res = ping.result.table
    ret = ping.result.raw
    retlist = list(ret.split('\n'))
    loss = retlist[2].split(',')[3].split(' ')[1]  # 获取数据包发送成功率
    return loss, res
     
def main():

    # 获取待ping的设备地址信息
    with open('C:\\Users\\Junson\\Desktop\\Script\\巡检\\门禁\\门禁设备列表.csv','r') as ipList_csv:
        ipList = csv.reader(ipList_csv)
        next(ipList)    #跳过首行
        for ipAddress in ipList:
            
            # 调用pingip方法得到数据包发送成功率
            loss, res = pingip(ipAddress[0], 4)
            if float(loss.strip('%')) / 100 <= 0.3:   # 0.3为自定义数据包丢包率阈值,可修改

                #数据包发送成功率低于30%时,发送消息到企微机器人
                SendWeiXinWork('@all','%s %s无法ping通,请检查设备的网络连接!'%(ipAddress[0],ipAddress[1]))
                
                #记录日志
                file_handle=open('C:\\Users\\Junson\\Desktop\\Script\\巡检\\门禁\\log.txt',mode='a')
                file_handle.write('\n%s   %s   %s无法ping通,请检查设备的网络连接!'%(datetime.now(),ipAddress[0],ipAddress[1]))
                file_handle.close()
            else:
                #记录日志
                file_handle=open('C:\\Users\\Junson\\Desktop\\Script\\巡检\\门禁\\log.txt',mode='a')
                file_handle.write('\n%s   %s   %sping访问正常。'%(datetime.now(),ipAddress[0],ipAddress[1]))
                file_handle.close()
                
 
if __name__ == '__main__':
    #实现服务器网络状态监控
    
    main()
    pass

csv文件结构

创建计划任务:

最终效果:

相关推荐
人工智能训练2 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
yaoming1682 小时前
python性能优化方案研究
python·性能优化
码云数智-大飞3 小时前
使用 Python 高效提取 PDF 中的表格数据并导出为 TXT 或 Excel
python
biuyyyxxx4 小时前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
极客数模4 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
小鸡吃米…6 小时前
机器学习中的代价函数
人工智能·python·机器学习
Li emily7 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
m0_561359677 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
vx-bot5556667 小时前
企业微信接口在多租户SaaS平台中的集成架构与数据隔离实践
大数据·架构·企业微信
Ulyanov7 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲