Python script sends alert message

Source: Internet
Author: User
Tags mail code stdin python script

Recently in the Nagios alarm mailbox Exchange to 163, Sina this free mailbox top, before used msmtp can also send mail, now estimate is their system is upgraded, can only use TSL encrypted connection, and msmtp how configuration is not available, helpless can only transfer tactics, Just recently in the study of Python, do not know where to see the module has an email, so prepare to try to make a script.

(Novice, no programming basis, hope more advice)

-----2016.1.4 Revision----

Premise:

Change the command configuration for sending messages in nagios/etc/object/command.cfg, such as Me:

#  ' Notify-host-by-email '  command definitiondefine command{         command_name    notify-host-by-email         command_line    /usr/bin/printf  "%b"   "host:  $HOSTNAME $\nstate:   $HOSTSTATE $\naddress:  $HOSTADDRESS $\ninfo:  $HOSTOUTPUT $\n\ndate/time:  $LONGDATETIME $\n "  | /usr/local/nagios/shell/sendemail.py -s  "$HOSTADDRESS $ is  $HOSTSTATE $"  - r  $CONTACTEMAIL $        } #  ' Notify-service-by-email '  command definition       define command{         command_name    notify-service-by-email         command_line    /usr/bin/printf  "%b"   "Service:   $SERVICEDESC $\nhost:  $HOSTALIAS $\naddress:  $HOSTADDRESS $\nstate:  $SERVICESTATE $\nadditional info: $ serviceoutput$\n\ndate/time:  $LONGDATETIME $\n " | /usr/local/nagios/shell/sendemail.py -s   "$HOSTADDRESS $/$SERVICEDESC $ is  $SERVICESTATE $"  -R  $CONTACTEMAIL $         }

#!/usr/bin/env python# -*- coding: utf-8 -*-# --2016.01.04-- v2.0#  Script to replace Nagios monitor send alert message # sendemail.py #  method:# printf  "Mail Content"  | sendemail.py  -s  "Mail Subject"  -R  recipient 1, Recipient 2import smtplib,sys,random,getoptfrom email.mime.text  Import mimetextdef sendemail (host, sender, ssl=true):    subject  =  '     receivers = []    host = host     sender = sender    copyto = [' [email protected] ',  ' [email protected] ',  ' [email protected] ',  ' [email protected] ',  ' [email  protected] ']    passwd =  ' password '      #参数获取收件人      try:        opts, args =  Getopt.getopt (sys.argv[1:],  ' s: R: ')         for i in opts:             if  '-S '  in i:                 subject = i[1]             elif  '-R '  in i:                 receivers.append (i[1])      except getopt. getopterror, e:        print e    # The following code snippet uses the Mimetext function to generate a message header format that provides some option configuration (Object.sendmail method)     body =  ' "when sending messages behind. Join (Sys.stdin.readlines ())     msg = mimetext (body)     msg[' Subject '] = subject    msg[' from '] = sender    msg [' tO '] =  ', '. Join (receivers)     msg[' cc '] =  ', '. Join (CopyTo)      receivers = receivers + copyto    if SSL :         port = 465         S = smtplib. Smtp_ssl (Host, port)     else :         Port = 25        s = smtplib. SMTP (Host, port)     s.login (sender, passwd)     s.sendmail ( Sender, receivers, msg.as_string ()) Def someone ():     backuplist =  [(' smtp.yourdomain.com ',  ' [email protected] '),   (' smtp.yourdomain.cn ',  ' [email  protected]]    some_one = random.choice (backuplist)      return some_One    def main ():    count = 0     while count <5 :        try:             sendemail (' mail.cipnet.cn ',  ' [email protected] ',  false)          except:             host,sender = someone ()              try:                 sendemail (Host,sender)              except:                 continue            else:                 break         else:             break             if __name__ ==  ' __main__ ':     main ()

Script slightly messy I was roughly divided into three parts

The first section, setting variables such as sender recipient topic

The second part, using the Mimetext function to format the message content subject such as message header format

The third part, log in the mailbox, send the mail code

If you do not want to take it, you can change the sender (sender variable), sender SMTP (host variable), sender password (pass variable), cc person (copyto variable, our company fixed several people so I directly to the mailbox script, you can also be written as parameter designation)

List several problems encountered

1, do not understand what the mimetext is exactly what is it generated what kind of a mail header?


>>> from email.mime.text import MIMEText>>> body =  ' 123456 ' >>> subject =  ' test mail ' >>> sender =  ' [email  protected] '       >>> receivers =  ' [email  Protected] ' >>> copyto =  ' [email protected] ' >>> msg =  Mimetext (body) >>> msg[' subject '] = subject>>> msg[' from '] =  sender>>> msg[' to '] = receivers>>> msg[' CC '] = copyto>> > print msgFrom nobody Tue Aug 11 10:54:59 2015Content-Type:  text/plain; charset= "Us-ascii" mime-version: 1.0content-transfer-encoding: 7bitsubject:  Test mailfrom: [email protected]to: [email protected]cc: [email protected] 123456

Just like this, is a plain text format, by the way, the Mimetext function can also specify the second parameter as the format, for example, HTML format, which can be referred to here:

Https://docs.python.org/2/library/email.mime.html#email.mime.text.MIMEText

2, the recipient can receive, CC people and the dark send people are not receiving?

This really tangled up a lot of time, and the key is that the recipient received the mail below is a copy of the person!

This makes me suspect that the Smtplib module does not support CC!

Later I found a vague answer that you want to add cc and Bcc to list! I feel sure can solve, and then I continue to check down, sure enough you only need the following line of code to do!

Receivers = receivers + CopyTo

The second parameter of the. SendMail method, which is the recipient parameter, specifies all the people who can receive the message, so we're going to merge the recipients, Cc's, and dark send together.

The specific person who is the recipient and CC has already been formatted in the Mimetext function and will be assigned to. SendMail's third parameter

You can refer to this:

Https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail

3, Python standard input readline and readlines difference

#!/usr/bin/env python#-*-coding:utf-8-*-# name:1.pyimport syswhile true:line = Sys.stdin.readline () if not Lin E:break Sys.stdout.write (line)--------------------------------------------------------------------------------- ---[[email protected] tmp]# printf "1\n2\n3" |./1.py 123
#!/usr/bin/env python#-*-coding:utf-8-*-# name:2.pyimport sysfor i in Sys.stdin.readlines (): Sys.stdout.write (i)-- -----------------------------------------------------------------------------------[[Email protected] tmp]# printf "1\n2\n3\n" |./2.py 123

difference between the. ReadLine () method and the. ReadLines () method (two methods are not part of the Sys.stdin method)

Therefore, the Python standard input and output issue is not discussed.

⑴, ReadLine is read in line until the end of the line break is encountered.

#!/usr/bin/env python#-*-coding:utf-8-*-# name:1.pyimport sysprint sys.stdin.readline ()--------------------------- ---------------------------------------------------------[[email protected] tmp]# printf "1" |./1.py 1[[email Protected] tmp]# printf "1\n" |./1.py 1[[email protected] tmp]# printf "1\n2" |./1.py 1[[email protected] tmp]# printf " 1\n\n "|./1.py 1

⑵, ReadLines reads everything, saves them as a list

#!/usr/bin/env python#-*-coding:utf-8-*-# name:2.pyimport sysprint sys.stdin.readlines ()-------------------------- ----------------------------------------------------------[[email protected] tmp]# printf "1\n2" |./2.py [' 1\n ', ' 2 '] [[email protected] tmp]# printf "1\n2\n" |./2.py [' 1\n ', ' 2\n ']

4. The Getopt function returns two tables, and the two tables are saved separately.

#-*-Coding:utf-8-*-# name:test.pyimport sys,getoptopts, args = Getopt.getopt (sys.argv[1:], ' s:r: ', [' Help ', ' text= ']) Print Optsprint args------------------------------------------------------------------------------------[[email Protected] tmp]#./test.py-s sss-r RRR--help--text abc[('-s ', ' SSS '), ('-R ', ' RRR '), ('--help ', '), ('--text ', ' abc ') ][][[email protected] tmp]#./test.py-s sss-r RRR--help--text ABC other-h[('-s ', ' SSS '), ('-R ', ' RRR '), ('--help ', ' ), ('--text ', ' abc ') [' Other ', '-h '] #这样看来第二个表格用来寸未定义的参数

parameter how to write reference here:

Https://docs.python.org/2/library/getopt.html#getopt.getopt


Python script sends alert message

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.