2 # arekm@pld-linux.org, 2006-01
3 # glen@pld-linux.org, 2006-03-14
4 # glen@pld-linux.org,arekm@pld-linux.org, 2006-10-30 - added ssl support (for gmail.com)
5 # glen@pld-linux.org 2006-11-03 - made it work with jabber.pld-linux.org again
6 # glen@pld-linux.org,arekm@pld-linux.org, 2006-11-13 - added config file support
7 # glen@pld-linux.org, 2006-12-07 - added html messages support (-x), thx goes to to jajcus
8 # luzik@pld-linux.org, 2007-03 - added digest auth method(jabber.gda.pl)
9 # arekm@pld-linux.org, 2009-07 - added fallback accounts support
11 # jabber.alert [-x] [-c config] [-a account_id][,otheraccount_id] [-t timeout ] [-J from_jid -P password] to_jid1 to_jid2 to_jid3
24 from pyxmpp.jid import JID
25 from pyxmpp.message import Message
26 from pyxmpp.jabber.client import JabberClient
27 from pyxmpp.streamtls import TLSSettings
30 opts, args = getopt.getopt(sys.argv[1:], "J:P:a:c:dt:x")
31 except getopt.GetoptError, e:
32 print >> sys.stderr, "%s: %s " % (sys.argv[0], e)
39 cfg = "/etc/nagios/jabber-notify.ini"
51 jids.append({ 'jid': tjid, 'password': a })
55 config = ConfigParser.ConfigParser()
58 for section in a.split(','):
59 jids.append({ 'jid': config.get(section, 'jid'), 'password': config.get(section, 'password')})
61 socket.setdefaulttimeout(timeout)
66 if not section['jid'] or not section['password']:
67 print >> sys.stderr, "%s: jid (-J) and password (-P) are required for `%s'" % (sys.argv[0], section)
71 print >> sys.stderr, "%s: no configured jid accounts found" % sys.argv[0]
75 print >> sys.stderr, "%s: recipient jids are required" % sys.argv[0]
79 logger=logging.getLogger()
80 logger.addHandler(logging.StreamHandler())
81 logger.setLevel(logging.DEBUG)
83 subject = "Nagios alert"
88 for line in sys.stdin.readlines():
93 if len(body.strip()) == 0:
94 body = "(nagios-jabber.alert warning: missing message body)";
98 class XMPPStreamError(Exception):
99 def __init__(self, msg):
104 class Client(JabberClient):
105 def session_started(self):
108 message = re.sub('<.*?>', '', body)
109 doc = libxml2.parseDoc('<body>' + body + '</body>')
110 doc_element = doc.getRootElement().children
116 msg = Message(to_jid = jid_r, body = message, subject = subject,
117 stanza_type = message_type, thread = "Nagios")
120 node = msg.add_new_content('http://jabber.org/protocol/xhtml-im', 'html')
121 xbody = node.newChild(None, "body", None)
122 html_ns = xbody.newNs('http://www.w3.org/1999/xhtml', None)
124 xbody.addChildList(doc_element.docCopyNodeList(xbody.doc))
126 self.stream.send(msg)
129 def stream_state_changed(self,state,arg):
131 print "*** State changed: %s %r ***" % (state,arg)
133 def stream_error(self,err):
134 raise XMPPStreamError(err.get_message())
139 for attempt in ('first', 'second'):
140 jid = JID(section['jid'])
141 resource = "Nagios/" + hashlib.md5(''.join(recpt)).hexdigest()[:10]
142 if attempt == 'second':
143 # if something went wrong the second time around, it's
144 # most likely a resource name conflict on login, so let's
145 # wait a bit, randomize the resource name and try again
146 resource = resource + '/' + repr(os.getpid())
149 jid = JID(jid.node, jid.domain, resource)
151 c = Client(jid, section['password'], auth_methods = ['sasl:DIGEST-MD5', 'sasl:PLAIN', 'digest'],
152 tls_settings = TLSSettings(require = False, verify_peer = False))
157 except XMPPStreamError, e:
158 # Most likely a duplicate stream problem
159 # don't log anything, just try again
163 err.append("ERROR1: %s: %s" % (section['jid'], e))
165 # don't try another attempt, jump straigt to
169 # stop after first successful attempt at sending the msg
172 err.append("ERROR2: %s: %s" % (section['jid'], e))
174 print >> sys.stderr, "\n".join(err)