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文件结构

创建计划任务:

最终效果:

相关推荐
自动化小秋葵20 小时前
Python入门经典题目
开发语言·python
while(1){yan}20 小时前
数据结构之堆
数据结构·python·算法
凌晨一点的秃头猪21 小时前
Python 常见 bug 总结和异常处理
开发语言·python·bug
mortimer21 小时前
用PySide6 构建一个响应式视频剪辑工具:多线程与信号机制实战
python·ffmpeg·pyqt
新子y21 小时前
【小白笔记】input() 和 print() 这两个函数
笔记·python
文火冰糖的硅基工坊21 小时前
[人工智能-大模型-72]:模型层技术 - 模型训练六大步:①数据预处理 - 基本功能与对应的基本组成函数
开发语言·人工智能·python
Python×CATIA工业智造1 天前
Pycatia二次开发基础代码解析:组件识别、选择反转与链接创建技术解析
python·pycharm
小宁爱Python1 天前
从零搭建 RAG 智能问答系统 6:Text2SQL 与工作流实现数据库查询
数据库·人工智能·python·django
m0_748241231 天前
Java注解与反射实现日志与校验
java·开发语言·python
可触的未来,发芽的智生1 天前
追根索源:换不同的词嵌入(词向量生成方式不同,但词与词关系接近),会出现什么结果?
javascript·人工智能·python·神经网络·自然语言处理