python使用Windows的wmic命令監控文件運行狀況,如有異常發送郵件報警
使用Windows的wmic命令,獲取可執行文件的運行狀況、文件路徑、PID,如果可執行文件掛掉,就重啟并郵件告警。
因為監控的可執行文件的文件名一樣,不好區分,所以我使用文件的絕對路徑為標準來判斷是否正常運行,代碼及詳細解釋如下:
# -*- coding: utf-8 -*- import osimport win32apiimport smtplibfrom email.mime.text import MIMETextdef 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 = 0for i in range(len(exe_info)): if file_path in exe_info[i][0]: pos = 1 else: passif pos == 1: passelse: 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循環來判斷file_path是否在我們 get_pidWay函數返回的列表中,從而知道可執行文件是否正常運行;
如果沒有運行,pos = 0,則運行文件、發送郵件。
以上就是python使用Windows的wmic命令監控文件運行狀況,如有異常發送郵件報警的詳細內容,更多關于python wmic命令監控文件運行狀況的資料請關注好吧啦網其它相關文章!