Python调用wmic监控Windows进程状态并实现异常重启与邮件告警

Elena
Elena
发布时间:2026-10-14 | 4人浏览过
原创

本文介绍如何利用Python调用Windows wmic命令获取可执行文件的PID、路径及运行状态。当检测到指定进程异常退出时,脚本自动通过win32api重启程序,并通过QQ SMTP服务器发送SSL加密的报警邮件。文中详细解析了进程查询、文件启动及邮件发送的核心代码逻辑,适用于内网环境下的服务稳定性监控。

利用Windows系统的wmic命令行工具,可以获取可执行文件的运行状态、文件路径以及进程ID(PID)。一旦检测到目标可执行文件进程意外终止,系统将自动执行重启操作,并通过邮件发送告警通知。

由于被监控的可执行文件可能具有相同的文件名,难以直接区分,因此本文采用文件的绝对路径作为判断进程是否正常运行的唯一标准。具体的代码实现及详细解释如下:


# -*- coding: utf-8 -*- 
import os
import win32api
import smtplib
from email.mime.text import MIMEText


def get_pidWay(file_name):
  ept_list = []
  temp_list = []
  pid_way = os.popen("wmic process where name='" + file_name + "' get processid,executablepath,name").readlines()
  for j in pid_way:
    temp_list.append(j.split())
  while ept_list in temp_list:
    temp_list.remove(ept_list)
  return(temp_list)
 
def open_file(filePath):
  win32api.ShellExecute(0, 'open', filePath, '','',1)

def mailsend (mailtext,mailsubject):
  mailserver = "smtp.qq.com"
  username_send = '发送的邮箱地址'
  password = '密码'
  username_recv = '接收的邮箱地址'
  mail = MIMEText(mailtext)
  mail['Subject'] = mailsubject
  mail['From'] = username_send
  mail['To'] = username_recv
  smtp = smtplib.SMTP_SSL(mailserver)
  smtp.login(username_send,password)
  smtp.sendmail(username_send,username_recv,mail.as_string())
  smtp.quit()
  print ('success')
  


file_path = "可执行文件的绝对路径"
fileName = '可执行文件名'
mailtext = '报警邮件内容'
mailsubject = '报警邮件标题'
exe_info = get_pidWay(fileName)
pos = 0
for i in range(len(exe_info)):
  if file_path in exe_info[i][0]:
    pos = 1
  else:
    pass

if pos == 1:
  pass
else:
  open_file(r"可执行文件名")
  mailsend(mailtext,mailsubject)

1. get_pidWay函数:

该函数接收file_name作为输入参数,返回包含文件路径、文件名及PID的列表。通过split函数处理ept_list字符串,将返回结果转换为二维数组格式,即[[文件路径,文件名,PID], [文件路径,文件名,PID]],以便后续遍历判断。

2. open_file函数:

调用win32api模块,其功能类似于在CMD命令行中执行程序,用于打开指定的可执行文件路径。

3. mailsend函数:

负责发送邮件告警。此处采用QQ邮箱的SMTP模块,用户需在QQ邮箱设置中开启SMTP服务端口以获取授权码。

username_send变量指定发送邮件的邮箱地址,password变量为开启SMTP服务时生成的授权字符串(非邮箱登录密码)。

username_recv变量指定接收报警邮件的邮箱地址。

在内网环境中,必须使用smtplib.SMTP_SSL(mailserver)进行连接,其中mailserver设置为'smtp.qq.com'。若使用smtp = smtplib.SMTP(mailserver, port=465)方式连接,通常会报错:smtplib.SMTPServerDisconnected: Connection unexpectedly closed。

4. 主函数逻辑:

file_path变量用于指定放置可执行文件的目录路径。

fileName变量用于指定可执行文件的名称。

通过for循环遍历get_pidWay函数返回的列表,检查file_path是否存在于列表中,以此判断可执行文件是否正在正常运行。

若文件未运行,则变量pos赋值为0。此时程序将执行文件启动操作并发送报警邮件。

以上即为使用Python调用Windows wmic命令监控文件运行状况、异常时自动重启并发送邮件报警的完整实现。更多关于Python wmic命令监控文件运行状况的资料,可参考本站其他相关文章。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表