使用python脚本实现,通过cgi命令获取剩余内存和句柄数,判断内存值与句柄数是否少于/超出临界值,若已少于/超出临界值则通过邮件的方式通知。
注:收发邮箱可自定义,若邮箱要开启加密,需同步修改代码中的邮箱服务器端口
ps:此脚本只应用于特殊版本,cgi接口是研发特地加的,标准版本无此接口,后续可考虑实现串口通信,应用于标准版本
import requests import re from requests.auth import HTTPBasicAuth import time import smtplib from email.mime.text import MIMEText # 最小报警内存值 alarm_free_memory = 30 def GetHttp(url_base,url_param,user,password): try: headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'} r = requests.get(url_base,auth=HTTPBasicAuth(user, password),params=url_param,headers=headers,timeout=5) r.raise_for_status() print(r.url) mem_text = r.text[0:len(r.text)-10] print(mem_text) # print("----------------------------") return mem_text # except requests.exceptions.ConnectionError as reason: # print('ConnectionError -- ' + str(reason)) # except requests.exceptions.ChunkedEncodingError: # print('ChunkedEncodingError') # except requests.exceptions.HTTPError as reason: # print('HTTPError' + str(reason)) except Exception as reason: print('HTTPError' + str(reason)) def send_email(email_text): #设置服务器所需信息 #163邮箱服务器地址 mail_host = 'smtp.163.com' #163用户名 mail_user = 'img1234' #密码(部分邮箱为授权码) mail_pass = 'ms1234' #邮件发送方邮箱地址 sender = 'img1234@163.com' #邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发 receivers = ['kayla@milesight.com'] #设置email信息 #邮件内容设置 message = MIMEText(email_text,'plain','utf-8') #邮件主题 message['Subject'] = 'IPC Alarm' #发送方信息 message['From'] = sender #接受方信息 message['To'] = receivers[0] #登录并发送邮件 try: smtpObj = smtplib.SMTP() #连接到服务器 smtpObj.connect(mail_host,25) #登录到服务器 smtpObj.login(mail_user,mail_pass) #发送 smtpObj.sendmail( sender,receivers,message.as_string()) #退出 smtpObj.quit() # print('success') except smtplib.SMTPException as e: print('error',e) #打印错误 if __name__ == '__main__': user = 'admin' password = 'dm123456' url_param = None while 1: url_base = "http://192.168.4.109/vb.htm?debugfree" mem_text = GetHttp(url_base, url_param, user, password) mem_array = re.findall(r"d+.?d*", mem_text) free_mem = int(mem_array[2]) if free_mem < alarm_free_memory: send_email(mem_text) time.sleep(5) url_base = "http://192.168.4.109/vb.htm?debugfd=msserver" fd_text = GetHttp(url_base, url_param, user, password) total_fd = int(fd_text[0:3]) if total_fd > 30: send_email(fd_text) time.sleep(5) url_base = "http://192.168.4.109/vb.htm?debugfd=avserver" fd_text = GetHttp(url_base, url_param, user, password) total_fd = int(fd_text[0:3]) if total_fd > 50: send_email(fd_text) time.sleep(30)