Python脚本打开进程但不发送邮件

时间:2014-12-19 07:51:55

标签: python email python-2.7 process

我正在制作一个脚本,用于检查程序是否正在运行,然后发送电子邮件进行确认。到目前为止,我的脚本只打开程序,但没有给我发电子邮件。我想更改为检查流程,然后发送电子邮件而不是打开程序。

import smtplib
import sys
import os
import csv
import subprocess
from subprocess import CalledProcessError, Popen, PIPE

# Set up mail info
FROM = "it@mail.com"
TO = ["mine@mail.com"] # must be a list
SUBJECTERR = "Batchserver runnning"
TEXTERR = "Batch server running" 
SUBJECT = "Batch Server status "
TEXT = "Batch Server running relax"

#Gives response
cmd = '\\\\sesrv414\\Applications\\Software\\BIN\\system.EXE'
p = Popen(cmd, stdin=PIPE, bufsize=0)
if p.returncode != 1:
  raise CalledProcessError(p.returncode, cmd)
  server = smtplib.SMTP("email.serv.net",25) # Send the mail
  messageErr = "From:%s \nTo:%s \nSubject:%s \n\n%s\n" %(FROM, ", ".join(TO), 
  SUBJECTERR,   TEXTERR)
  server.sendmail(FROM, TO, messageErr)
  server.quit()
  raise

 sys.stderr.close();
 sys.stderr = sys.__stderr__

1 个答案:

答案 0 :(得分:1)

由于您在发送电子邮件之前提出了异常。

您必须首先安装psutil以检查Windows操作系统中的进程。 如果您的流程名称不是' system.EXE',则必须在代码中更改变量name的值。

试试这个:

import smtplib
import sys
import os
import csv
import subprocess
from subprocess import CalledProcessError, Popen, PIPE
import psutil
import re

# Set up mail info
FROM = "it@mail.com"
TO = ["mine@mail.com"] # must be a list
SUBJECTERR = "Batchserver runnning"
TEXTERR = "Batch server running" 
SUBJECT = "Batch Server status "
TEXT = "Batch Server running relax"

#Gives response

name = "system.EXE"

running = False
for process in psutil.process_iter():
    if re.search(name, repr(process)):
        running = True
        break
if not running:
    cmd = '\\\\sesrv414\\Applications\\Software\\BIN\\system.EXE'
    p = Popen(cmd, stdin=PIPE, bufsize=0)    


server = smtplib.SMTP("email.serv.net",25) # Send the mail
messageErr = "From:%s \nTo:%s \nSubject:%s \n\n%s\n" %(FROM, ", ".join(TO), 
SUBJECTERR,   TEXTERR)
server.sendmail(FROM, TO, messageErr)
server.quit()


sys.stderr.close();
sys.stderr = sys.__stderr__