【问题标题】:Issue with SMTP lib in python3.6python3.6中的SMTP库问题
【发布时间】:2020-07-01 11:38:45
【问题描述】:

我的 python 监控脚本有一个奇怪的问题:- 我已经为任何服务器编写了一个包含许多警报的脚本。在那我有一个收集网络字节/秒进出的功能。 现在的问题是,当我在邮件函数之外打印警报时,它会打印当前输出,但由于某种原因,当它触发警报邮件时,邮件正文为空。如果我使用不在网络功能中的另一个警报触发邮件,它会正常工作。 还有一种方法可以让 smtplib 使用端口 587 而不是 465,任何有关格式化警报的指针也将不胜感激。 请在下面找到我的脚本:-

#!/usr/bin/env python3
#Module psutil needs to be installed via pip3 first.
#Python script to Monitor Server Resources.

import time
import psutil
import smtplib
from email.message import EmailMessage

project_and_instance_name = 'test-stage' #Edit the name of the project name and environment
sender = '<sender email>' #Email Address of the sender
receivers = ['recepient email'] #comma seperated list of recipients enclosed in ''

cpu_thresh = 50.0
cpu_pct = psutil.cpu_percent(interval=1)

if cpu_pct >= cpu_thresh:
    cpu_alert = "CPU Warning, CPU at ",cpu_pct, "percent"
else:
    cpu_alert = ""

mem = psutil.virtual_memory()
mem_thresh = 1024 * 1024 * 1024 #change the end value to choose the amount of MB

if mem_thresh >= mem.available:
    mem_alert = "Memory Usage Warning only", round((mem.available /1024 /1024), 2), "MB available"
else:
    mem_alert = ""
partition1 = '/'
disk1 = psutil.disk_usage(partition1)
disk_thresh = 85.0

if disk_thresh <= disk1[3]:
    disk_alert = f"Root volume usage warning {disk1[3]} % used"
else:
    disk_alert = ""

def net_usage(inf = "eth0"):   #change the inf variable according to the interface
  global net_in_alert
  global net_out_alert
  net_in_ps1 = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
  net_in_1 = net_in_ps1.bytes_recv
  net_out_1 = net_in_ps1.bytes_sent
  time.sleep(1)
  net_in_ps2 = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
  net_in_2 = net_in_ps2.bytes_recv
  net_out_2 = net_in_ps2.bytes_sent
  net_in_res = round((net_in_2 - net_in_1) /1024 /1024, 2)
  net_out_res = round((net_out_2 - net_out_1) /1024 /1024, 2)
  net_in_thresh = 1.5
  net_out_thresh = 1.5
  if net_in_res >= net_in_thresh:
      net_in_alert = f"Current net-usage:IN: {net_in_res} MB/s"
  else:
      net_in_alert = ""
  if net_out_res <= net_out_thresh:
     net_out_alert = f"Current net-usage:OUT: {net_out_res} MB/s"
  else:
      net_out_alert = ""
net_usage()

message_list = []

if cpu_alert == "" :
    pass
else:
    message_list.append(cpu_alert)
if mem_alert == "" :
    pass
else:
    message_list.append(mem_alert)
if disk_alert == "" :
    pass
else:
    message_list.append(disk_alert)
if net_in_alert == "" :
    pass
else:
    message_list.append(net_in_alert)
if net_out_alert == "" :
    pass
else:
    message_list.append(net_out_alert)

msg = '\n'.join(message_list)
print(msg)

def alerts():
  server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
  server.login(sender, "<password>")
  server.sendmail(sender,receivers,msg)

if msg == "":
  pass
else:
  alerts()

【问题讨论】:

    标签: python-3.6 smtplib


    【解决方案1】:

    通过更改任何卡在此处的任何人的 SMTP 格式得到答案是代码:-

    #!/usr/bin/env python3
    #Module psutil needs to be installed via pip3 first.
    #Python script to Monitor Server Resources.
    
    import time
    import psutil
    import smtplib, ssl
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    project_and_instance_name = 'test-stage' #Edit the name of the project name and environment
    sender = '<senders email>' #Email Address of the sender
    receivers = ['recepient email'] #comma seperated list of recipients enclosed in ''
    
    cpu_thresh = 50.0
    cpu_pct = psutil.cpu_percent(interval=1)
    
    if cpu_pct >= cpu_thresh:
        cpu_alert = "CPU Warning, CPU at ",cpu_pct, "percent"
    else:
        cpu_alert = ""
    
    mem = psutil.virtual_memory()
    mem_thresh = 1024 * 1024 * 1024 #change the end value to choose the amount of MB
    
    if mem_thresh >= mem.available:
        mem_alert = "Memory Usage Warning only", round((mem.available /1024 /1024), 2), "MB available"
    else:
        mem_alert = ""
    partition1 = '/'
    disk1 = psutil.disk_usage(partition1)
    disk_thresh = 85.0
    
    if disk_thresh <= disk1[3]:
        disk_alert = f"Root volume usage warning {disk1[3]} % used"
    else:
        disk_alert = ""
    
    def net_usage(inf = "eth0"):   #change the inf variable according to the interface
      global net_in_alert
      global net_out_alert
      net_in_ps1 = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
      net_in_1 = net_in_ps1.bytes_recv
      net_out_1 = net_in_ps1.bytes_sent
      time.sleep(1)
      net_in_ps2 = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
      net_in_2 = net_in_ps2.bytes_recv
      net_out_2 = net_in_ps2.bytes_sent
      net_in_res = round((net_in_2 - net_in_1) /1024 /1024, 2)
      net_out_res = round((net_out_2 - net_out_1) /1024 /1024, 2)
      net_in_thresh = 1.5
      net_out_thresh = 1.5
      if net_in_res >= net_in_thresh:
          net_in_alert = f"Current net-usage:IN: {net_in_res} MB/s"
      else:
          net_in_alert = ""
      if net_out_res >= net_out_thresh:
         net_out_alert = f"Current net-usage:OUT: {net_out_res} MB/s"
      else:
          net_out_alert = ""
    net_usage()
    
    message_list = []
    
    if cpu_alert == "" :
        pass
    else:
        message_list.append(cpu_alert)
    if mem_alert == "" :
        pass
    else:
        message_list.append(mem_alert)
    if disk_alert == "" :
        pass
    else:
        message_list.append(disk_alert)
    if net_in_alert == "" :
        pass
    else:
        message_list.append(net_in_alert)
    if net_out_alert == "" :
        pass
    else:
        message_list.append(net_out_alert)
    
    msg = '\n'.join(message_list)
    print(msg)
    
    def alerts():
      msg_template = MIMEMultipart()
      msg_template['From'] = sender
      msg_template['To'] = ', '.join(receivers)
      msg_template['Subject'] = f"{project_and_instance_name} Alert"
      msg_template.attach(MIMEText(msg, 'plain'))
      server = smtplib.SMTP('smtp.gmail.com', 587)
      server.ehlo()
      server.starttls()
      server.ehlo()
      server.login(sender, "<password>")
      server.sendmail(sender,receivers,msg_template.as_string())
      server.quit()
    
    if msg == "":
      pass
    else:
      alerts()
    

    【讨论】:

    【解决方案2】:

    对我理解这个答案有帮助 -

    receivers 是电子邮件列表

    receivers = ['email1', 'email2']
    



    消息模板 ["To"] 是一个连接字符串

    msg_template['To'] = ', '.join(receivers)
    



    server.sendmail() 是电子邮件列表

    server.sendmail(sender,receivers,msg_template.as_string())
    

    【讨论】:

    • 正确,receivers 是一个逗号分隔的列表。 msg_template['To'] join 将列表转换为逗号分隔的字符串。 server.sendmail 是 smtplib 用来实际发送电子邮件的方法,格式为发送者、接收者和任何消息(必须是字符串)。
    猜你喜欢
    • 1970-01-01
    • 2023-02-14
    • 2022-01-09
    • 2019-08-20
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多