欢迎光临散文网 会员登陆 & 注册

0基础上手python编程,实践进程+URL守护程序+企业微信机器人告警

2023-05-15 19:36 作者:王忘杰-王土狗  | 我要投稿

全民制作人大家好,我是学习python两天半的练习生王忘杰,喜欢路由交换、linux、网络安全,开整!这是我的第三篇0基础python文章,请大家支持,谢谢~

开发思路
用于监控指定的URL或进程,在我的场景中,使用了httpprinter打印机插件,这个程序提供了http接口的打印功能,当程序死机时,http接口无法连接,则需要重启程序
设计思路很简单,访问失败发送告警并重启程序即可。

绘制开发流程图

使用python语言实现

import os,requests,win32api,json,psutil

def process_check(processname):
   #检查进程是否存在,存在返回1
   pl = psutil.pids()
   for pid in pl:
       if psutil.Process(pid).name() == processname:
           return 1
   else:
       return 0

def url_check(url):
   #检查URL
   try:
       r = requests.get(url, timeout=3, verify=False)
       if r.status_code == 200:
           print("运行中,无异常")
       else:
           msg = "http打印程序状态异常,重启程序"
           yun_push(msg)
           # 关闭程序
           os.system("taskkill /F /IM HttpPrinter.exe")
           # 启动程序
           win32api.ShellExecute(0,'open','C:\\HttpPrinter_latest\\HttpPrinter.exe','','',1)
   except:
       msg = "http打印程序状态异常,重启程序"
       yun_push(msg)
       # 关闭程序
       os.system("taskkill /f /im HttpPrinter.exe")
       # 启动程序
       win32api.ShellExecute(0,'open','C:\\HttpPrinter_latest\\HttpPrinter.exe','','',1)

def yun_push(content):
   #企业微信推送
   url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的'
   s = json.dumps({'msgtype': 'text', 'text': {"content": content}})
   print(requests.post(url, data=s).text)


if __name__ == '__main__':
   #检查进程是否存在
   #if(process_check("HttpPrinter.exe"))

   #检查URL
   url_check("http://10.0.0.1:1234/")

编译成EXE程序
pyinstaller -F -w .\main.py

部署windows计划任务

运行效果



0基础上手python编程,实践进程+URL守护程序+企业微信机器人告警的评论 (共 条)

分享到微博请遵守国家法律