首页 > nagios > python插件做nagios发报警邮件

python插件做nagios发报警邮件

2010年12月17日 eric 发表评论 阅读评论

Ps: 完美的解决了python传入参数带有回车换行符,不换行问题。修改本文时间:2010年12月21号,脚本有变动·nagios commands.cfg无需修改·用了此版本·就解决了不用去读文本方式。

安装好nagios后,一直利用nagios服务器上的sendmail服务器去发邮件,修改配置文件可以伪造别的邮件地址发邮件,但是一直会被邮局视为垃圾邮件,我把email地址加在了QQ上,好处是一来邮件QQ右下角会弹提示。工作时间会第一时间知道服务器出状况(手机短信暂时不提),但是如果是垃圾邮件,QQ不会提醒的,当然可以在QQ邮箱把其添加为信任邮局,可以避免。我就不那么浪费时间了。自己写一个发邮件的插件来替换掉本机的sendmail服务,可以为服务器节省资源,大家也知道启动sendmail服务稍稍费点时间,如果主机名没有设置好的话sendmail服务会启动很久才能起来的哦。废话不多说了,发源代码。

nagios $> cat /usr/local/nagios/libexec/sendmail
#!/usr/bin/python
#Script is Sendmail
#Version 1.0.2
#BY:eric
#QQ:277057817
#coding=utf-8

import smtplib
import string
import sys
import getopt

def usage():
   print """sendmail is a send mail Plugins
   Usage:

   sendmail [-h|--help][-t|--to][-s|--subject][-m|--message]

   Options:
          --help|-h)
                 print sendmail help.
          --to|-t)
                 Sets sendmail to email.
          --subject|-s)
                  Sets the mail subject.
          --message|-m)
                  Sets the mail body
    Example:
           only one to email  user
          ./sendmail -t 'eric@nginxs.com' -s 'hello eric' -m 'hello eric,this is sendmail test!
           many to email  user
          ./sendmail -t 'eric@nginxs.com,yangzi@nginxs.com,zhangsan@nginxs.com' -s 'hello eric' -m 'hello eric,this is sendmail test!"""
   sys.exit(3)

try:
   options,args = getopt.getopt(sys.argv[1:],"ht:s:m:",["help","to=","subject=","message="])
except getopt.GetoptError:
   usage()
for name,value in options:
    if name in ("-h","--help"):
       usage()
    if name in ("-t","--to"):
# accept message user
       TO = value
       TO = TO.split(",")
    if name in ("-s","--title"):
       SUBJECT = value
    if name in ("-m","--message"):
       MESSAGE = value
       MESSAGE = MESSAGE.split('\\n')        #以‘\n’字符切割字符串,分割后的字符串python就不会在加\
       MESSAGE = '\n'.join(MESSAGE)          #在每个字符串后加 '\n' 字符,这样python 就会认为字符'\n'是换行符

#smtp HOST
HOST = "smtp.126.com"               #改为你的邮局SMTP 主机地址
#smtp port
PORT = "25"                               #改为你的邮局的SMTP 端口
#FROM mail user
USER = 'eric'                              # 改为你的邮箱用户名
#FROM mail password
PASSWD = '123456'                    # 改为你的邮箱密码
#FROM EMAIL
FROM = "yangzi2008@126.com"    # 改为你的邮箱 email

try:
   BODY = string.join((
      "From: %s" % FROM,
      "To: %s" % TO,
      "Subject: %s" % SUBJECT,
      "",
      MESSAGE),"\r\n")

   smtp = smtplib.SMTP()
   smtp.connect(HOST,PORT)
   smtp.login(USER,PASSWD)
   smtp.sendmail(FROM,TO,BODY)
   smtp.quit()
except:
   print "UNKNOWN ERROR"
   print "please look help"
   print "./sendmail -h"

使用方法:
只给一个用户发:

nagios $> ./sendmail -t 'eric@nginxs.com' -s 'hello eric' -m 'hello eric,this is sendmail test!

给多个用户发:

./sendmail -t 'eric@nginxs.com,yangzi@nginxs.com,zhangsan@nginxs.com' -s 'hello eric' -m 'hello eric,this is sendmail test!

如果利用在nagios 上修改 commands.cfg
# 还为测试·马上就测试。怕的是换行符有问题·

nagios $> vim /usr/local/nagios/etc/objects/commands.cfg
define command{
        command_name    notify-host-by-email
        command_line    $USER1$/sendmail -t $CONTACTEMAIL$ -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **"  -m  "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n"
        }

define command{
        command_name    notify-service-by-email
        command_line    $USER1$/sendmail -t  $CONTACTEMAIL$ -s "** $NOTIFICATIONTYPE$ Service Alert: $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$ **"  -m  "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\n\nService: $SERVICEDESC$\nHost: $HOSTALIAS$\nAddress: $HOSTADDRESS$\nState: $SERVICESTATE$\n\nDate/Time: $LONGDATETIME$\n\nAdditional Info:\n\n$SERVICEOUTPUT$"
        }

有图有真相:

插件下载地址

sendmail

转载请注明:文章转载自:Eric's linux and nginx! (http://www.nginxs.com)
本文地址:http://www.nginxs.com/linux/371.html

分类: nagios 标签: , ,
  1. 2018年5月5日03:33 | #1

    Greetings from 온라인카지노카지노사이트온라인카지노California!
    I’m bored to death at work so I decided to check out your website on my iphone during lunch break.
    I love tthe knowledge you present here and can’t wait to take a look when I
    get home. I’m shocked at how quick your bblog loaded on my mobile ..
    I’m not eve using WIFI, just 3G .. Anyhow, great blog!

  2. 2018年5月5日03:42 | #2

    Way cool! Some extremely valid points! I appreciate you
    penning this post and also the rest of the site is really
    good.

  3. 2018年5月5日03:57 | #3

    When I initially commented I appear to have clicked the -Notify me when new comments are added- checkbox and from now on each time a comment is added I recieve 4 emails with the exact same comment.
    Is there an easy method you can remove me from that service?
    Appreciate it!

  4. 2018年5月5日04:08 | #4

    Way cool! Some very valid points! I appreciate you penning this article plus the
    rest of the website is very good.

  5. 2018年5月5日04:10 | #5

    Just wish to say your article is as amazing. The clearness in your submit is
    simply nice and i could assume you are an expert in this subject.

    Fine together with your permission let me to snatch your feed to keep up to
    date with imminent post. Thanks 1,000,000 and please keep up the gratifying work.

  6. 2018年5月5日04:46 | #6

    Its not my first time to pay a quick visit this website, i am
    browsing this website dailly and take fastidious information from
    here every day.

  7. 2018年5月5日04:53 | #7

    Juѕt wish to say your article is as amazing. Thе claгity for your pսt uuρ is
    sіmply cool and that i could think you are an experrt on this subject.
    Fine along with our permission allow mee to snatcһ your RSS feed to stay updated with forthcoming post.
    Thank yyou a million and рlease continue the rewarding work. http://www.3789789.com/comment/html/?373218.html

  8. 2018年5月5日05:03 | #8

    Tinted home windows supply a number of benefits.

  9. 2018年5月5日05:13 | #9

    play casino games online
    casino games real money
    casino games slots
    casinos online

  10. 2018年5月5日06:03 | #10

    real canadian superstore flyer
    top rated online canadian pharmacies
    canadian pharmacy online

  11. 2018年5月5日06:07 | #11

    Ⲥan I just sаy what a comfort to ffind a pеrѕon that rеally knows what they’rе discujssing
    online. You definiteⅼy гealize how to bring a proЬlem
    to light and make it important. More peopl need to check tthіs out andd understand this side of your story.

    It’s surpriѕing y᧐u’rе not more popular given that yоu mmost certainly have the gift. http://www.wangboshi.cc/comment/html/?1150495.html

  12. 2018年5月5日06:09 | #12

    My brother recommended I might like this blog. He was totally right.
    This post truly made my day. You can not imagine simply how much
    time I had spent for this info! Thanks!

  13. 2018年5月5日06:16 | #13

    Woah! I’m really loving the template/theme of this website.

    It’s simple, yet effective. A lot of times it’s difficult to get that
    “perfect balance” between usability and appearance.
    I must say you’ve done a fantastic job with this.

    In addition, the blog loads extremely fast for me on Safari.

    Exceptional Blog!

  14. 2018年5月5日06:23 | #14

    Hi! I could have sworn I’ve been to this website before but after reading
    through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely delighted I found it and I’ll be bookmarking and
    checking back frequently!

  15. 2018年5月5日06:57 | #15

    The other day, while I was at work, my cousin stole my iphone
    and tested to see if it can survive a 40 foot drop, just so she can be a
    youtube sensation. My iPad is now broken and she has 83 views.
    I know this is entirely off topic but I had to share it with someone!

  16. 2018年5月5日07:13 | #16

    I am curious to find out what blog system you have been working
    with? I’m experiencing some minor security issues with my latest blog and I’d like
    to find something more risk-free. Do you have any suggestions?

  17. 2018年5月5日07:15 | #17

    Very energetic post, I loved that a lot. Will there be a part 2?

  18. 2018年5月5日07:27 | #18

    I do consider all of the concepts you’ve introduced to your post.
    They are really convincing and can definitely work. Still, the posts are too quick for beginners.
    May just you please extend them a bit from subsequent time?
    Thanks for the post.

  19. 2018年5月5日07:28 | #19

    We stumbled over here from a different web page and thought I should check things out. I like what I see so now i am following you. Look forward to looking into your web page repeatedly.

  20. 2018年5月5日07:35 | #20

    Wow that was unusual. I just wrote an extremely long comment but
    after I clickewd submit my coment didn’t show up. Grrrr…
    well I’m not writing all that over again.
    Anyways, just wanted to say wonderful blog!

  21. 2018年5月5日07:38 | #21

    Thank you for the auspicious writeup. It in fact was once a
    entertainment account it. Glance advanced to more delivered agreeable from you!
    However, how can we be in contact?

  22. 2018年5月5日07:47 | #22

    Having read this I believed it was extremely informative.
    I appreciate you taking the time and effort to put this article together.

    I once again find myself spending a lot of time both reading and commenting.

    But so what, it was still worthwhile!

  23. 2018年5月5日07:52 | #23

    casino online
    free casino games and poker
    online casino slots
    pogo casino slots

  24. 2018年5月5日08:09 | #24

    For newest news you have to pay a quick visit world-wide-web and on the web I found this site as a best website for hottest updates.

  25. 2018年5月5日08:20 | #25

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog
    that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and
    was hoping maybe you would have some experience with something like this.

    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward
    to your new updates.

  26. 2018年5月5日08:30 | #26

    I pay a quick visit every day some websites and
    websites to read posts, however this weblog presents quality based writing.

  27. 2018年5月5日08:34 | #27

    Ѕome times iits a pain inn the ass to read what weƄsite owners wrote but this site iss real ᥙser
    friendly!

  28. 2018年5月5日09:30 | #28

    I visit every day a few websites and blogs to read articles, but
    this blog presents feature based writing.

  29. 2018年5月5日09:37 | #29

    Great article and right to the point. I don’t know if this is in fact the best place to ask but
    do you people have any ideea where to employ some professional writers?
    Thx :)

  30. 2018年5月5日09:56 | #30

    I think that what you posted made a great deal of sense. However, what about this?
    suppose you were to create a killer headline? I mean, I
    don’t want to tell you how to run your website, however what if you added a
    post title that makes people desire more? I mean Eric's linux
    and nginx! » python插件做nagios发报警邮件 is a little plain. You should glance at
    Yahoo’s home page and note how they create news headlines to get
    viewers to open the links. You might add a video or a pic or two to get readers excited about everything’ve got
    to say. In my opinion, it could make your blog a little bit more interesting.

  31. 2018年5月5日09:59 | #31

    Nice post. I learn something new and challenging on websites I stumbleupon everyday.
    It will always be interesting to read through content from other authors and use something from other web sites.

  32. 2018年5月5日10:07 | #32

    Fantastic beat ! I would like to apprentice whilst you amend your site,
    how could i subscribe for a weblog website? The account helped me
    a acceptable deal. I had been tiny bit acquainted of this your broadcast provided shiny
    clear concept

  33. 2018年5月5日10:24 | #33

    Ηello, I do think your wеbsite might be having browѕer compatibіlity problems.

    When I take а look at your site in Safari, it looks fine
    however when oрening in I.E., it has some overⅼaрping issues.
    I merely wаnted to give you a quick heads up! Other than that,
    fantastic site!

  34. 2018年5月5日10:37 | #34

    Hello! Someone in my Facebook group shared this website with us so I cazme to check it out.
    I’m definitely enjlying the information. I’m book-marking and will be tweeting this tto myy followers!
    Outstanding blog and outstanding design and style.

  35. 2018年5月5日10:51 | #35

    I am curious to find out what blog system you have been using?
    I’m having some small security issues with my latest blog and I’d like to find something more risk-free.

    Do you have any recommendations?

  36. 2018年5月5日11:04 | #36

    casino online
    pogo casino slots
    online casino
    play casinos

  37. 2018年5月5日11:24 | #37

    Good way of telling, and good post to obtain information concerning my
    presentation focus, which i am going to convey in academy.

  38. 2018年5月5日11:37 | #38

    An outstanding share! I’ve just forwarded this onto a friend who has been conducting
    a little research on this. And he in fact ordered me breakfast simply because I stumbled upon it
    for him… lol. So allow me to reword this….

    Thanks for the meal!! But yeah, thanks for spending some time to talk
    about this issue here on your web page.

  39. 2018年5月5日11:37 | #39

    Hi mates, its fantastic post regarding cultureand completely explained, keep it up all the time.

  40. 2018年5月5日11:43 | #40

    I all the time emailed this weblog post page to all my associates, because if like to read it after that my contacts will
    too.

  41. 2018年5月5日11:44 | #41

    Hi, Neаat post. There’s a problem wіth your
    website in ijternet explorer, would tеst this? IE nonetheless is
    the marketplaϲe leader and a big component of other
    folks ill miѕxs your magnificent writing becazuse of this probⅼem.

  42. 2018年5月5日11:50 | #42

    It’s actually very difficult in this active life to listen news
    on TV, thus I only use world wide web for that purpose, and
    take the most recent news.

  43. 2018年5月5日11:53 | #43

    Hey! I know this is somewhat off topic but I was wondering if
    you knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having problems finding one?

    Thanks a lot!

  44. 2018年5月5日11:58 | #44

    I just couldn’t depart your website because I really enjoyed the standard
    information a person provide for your visitors? Is going to be back often so
    as to inspect new posts

  45. 2018年5月5日12:15 | #45

    Attractive portion of content. I just stumbled upon your web site and in accession capital to claim that
    I acquire in fact loved account your weblog posts. Any way I will be subscribing on your augment or even I
    fulfillment you get admission to persistently fast.

  46. 2018年5月5日12:42 | #46

    This text is worth everyone’s attention. When can I find out
    more?

  47. 2018年5月5日12:58 | #47

    Hi there mates, its enormous piece of writing regarding
    educationand entirely explained, keep it up all the time.

  48. 2018年5月5日13:00 | #48

    Oh my goodness! Impressive article dude! Thank you so much, However I am having problems with your RSS.
    I don’t know why I can’t join it. Is there anybody else getting identical RSS issues?
    Anyone who knows the answer will you kindly respond?
    Thanks!!

  49. 2018年5月5日13:03 | #49

    Helpful info. Lucky me I found your site unintentionally, and
    I am surprised why this coincidence did not happened
    earlier! I bookmarked it.

  50. 2018年5月5日13:10 | #50

    If you desire to grow your knowledge just keep visiting this web page and be updated with the hottest news update posted here.

评论分页
订阅评论
5+4= (必填)