代码改变世界

pyhon脚本监控远程服务器存活情况,异常发送钉钉告警

2024-04-22 14:17  ndzj  阅读(36)  评论(0编辑  收藏  举报
#!/usr/bin/python
#! _*_ coding:utf-8 _*_

import os
import time
from collections import Counter
from datetime import datetime
host = 'localhost'


ips = ['192.168.xx.70','192.168.xx.83','172.16.xx.107']

def ping(ip):
   #response = os.system("ping -n 1 %s" %( host)).read()
   response = os.popen('ping %s -w 1|grep ttl|wc -l' %(ip)).read().strip()
   if response == str(0):
      return response
def net_tie_in(check_time,gateway):
   list_0 = []
   for fn in range(check_time): #连续判断本机器和网关是否通
      time.sleep(1)
      if ping(gateway) == '0':
         list_0.append(gateway)
      else: #只要不是连续check_time秒不通,则退出for循环
         break
   return list_0


def dingding(ding_msg):
   os.system("/usr/bin/curl  https://oapi.dingtalk.com/robot/send?access_token=8b5cc0adxxxxxx950xxxxxxxxxxxxxxa3559058fe9xxxxxxxxxxxxxxx7bxxxxxxxx  -H \"Content-Type: application/json\" -d \"{'msgtype': 'text', 'at': {'atMobiles': ['138xxxxxx00'], 'isAtAll': false}, 'text': {'content': \'%s\'}}\" " %(ding_msg))

ctime = 6 #检查时间
ding_msg = 'Yearning-pro_边缘服务器mongodb_IP连通性检测'
for ip in ips:
   iplist = net_tie_in(ctime,ip)
   if iplist: #判断非空列表
      unique_list = list(set(iplist))
      for ipd in unique_list:
         ding_msg = 'Yearning-pro_xx项目mongodb_IP连通性检测,服务器%s网络不通请注意查看!!!'%(ipd)
         dingding(ding_msg)