3 # jabber.alert [-x] [-c config] [-a account_id][,otheraccount_id] [-t timeout ] [-J from_jid -P password] to_jid1 to_jid2 to_jid3
17 from pyxmpp2.jid import JID
18 from pyxmpp2.message import Message
19 from pyxmpp2.client import Client
20 from pyxmpp2.settings import XMPPSettings
21 from pyxmpp2.interfaces import EventHandler, event_handler, QUIT
22 from pyxmpp2.streamevents import AuthorizedEvent, DisconnectedEvent
25 opts, args = getopt.getopt(sys.argv[1:], "J:P:a:b:c:ds:t:x")
26 except getopt.GetoptError as e:
27 print("%s: %s " % (sys.argv[0], e), file=sys.stderr)
34 cfg = "/etc/nagios/jabber-notify.ini"
37 subject = "Nagios alert"
52 jids.append({ 'jid': tjid, 'password': a })
58 config = configparser.ConfigParser()
61 for section in a.split(','):
62 jids.append({ 'jid': config.get(section, 'jid'), 'password': config.get(section, 'password')})
64 socket.setdefaulttimeout(timeout)
69 if not section['jid'] or not section['password']:
70 print("%s: jid (-J) and password (-P) are required for `%s'" % (sys.argv[0], section), file=sys.stderr)
74 print("%s: no configured jid accounts found" % sys.argv[0], file=sys.stderr)
78 print("%s: recipient jids are required" % sys.argv[0], file=sys.stderr)
82 logger=logging.getLogger()
83 logger.addHandler(logging.StreamHandler())
84 logger.setLevel(logging.DEBUG)
88 for line in sys.stdin.readlines():
93 if len(body.strip()) == 0:
94 body = "(nagios-jabber.alert warning: missing message body)";
96 class NagiosHandler(EventHandler):
97 """Echo Bot implementation."""
99 signal.signal(signal.SIGINT, self.exit_gracefully)
100 signal.signal(signal.SIGTERM, self.exit_gracefully)
103 """Request client connection and start the main loop."""
104 self.client.connect()
107 def exit_gracefully(self, signum, frame):
108 logging.info(u"Received signal {0}".format(signum))
109 self.client.main_loop.quit()
111 def disconnect(self):
112 """Request disconnection and let the main loop run for a 2 more
113 seconds for graceful disconnection."""
114 self.client.disconnect()
115 self.client.run(timeout = 2)
117 @event_handler(AuthorizedEvent)
118 def handle_authorized(self, event):
121 message = re.sub('<.*?>', '', body)
122 doc = libxml2.parseDoc('<body>' + body + '</body>')
123 doc_element = doc.getRootElement().children
129 msg = Message(to_jid = jid_r, body = message, subject = subject,
130 stanza_type = 'chat', thread = "Nagios")
133 node = msg.add_new_content('http://jabber.org/protocol/xhtml-im', 'html')
134 xbody = node.newChild(None, "body", None)
135 html_ns = xbody.newNs('http://www.w3.org/1999/xhtml', None)
137 xbody.addChildList(doc_element.docCopyNodeList(xbody.doc))
139 event.stream.send(msg)
140 event.stream.disconnect()
142 @event_handler(DisconnectedEvent)
143 def handle_disconnected(self, event):
144 """Quit the main loop upon disconnection."""
148 def handle_all(self, event):
149 """Log all events."""
150 logging.info(u"-- {0}".format(event))
154 for attempt in ('first', 'second'):
155 jid = JID(section['jid'])
156 resource = "Nagios/" + hashlib.md5(''.join(recpt).encode('utf-8')).hexdigest()[:10]
157 if attempt == 'second':
158 # if something went wrong the second time around, it's
159 # most likely a resource name conflict on login, so let's
160 # wait a bit, randomize the resource name and try again
161 resource = resource + '/' + repr(os.getpid())
164 jid = JID(jid.local, jid.domain, resource)
166 settings = XMPPSettings({
167 u"password": section['password'],
168 u"software_name": "Nagios notify jabber",
170 u"tls_verify_peer": True,
171 u"tls_cacert_file": "/etc/pki/tls/certs/ca-bundle.crt"
174 handler = NagiosHandler()
176 c = Client(jid, [handler], settings)
180 except KeyboardInterrupt:
182 logging.info(u"Disconnected due to KeyboardInterrupt")
184 except Exception as e:
185 err.append("ERROR1: %s: %s" % (jid, e))
186 # don't try another attempt, jump straigt to
191 logging.info(u"Disconnected")
192 # stop after first successful attempt at sending the msg
194 except Exception as e:
195 err.append("ERROR2: %s: %s" % (jid, e))
197 print("\n".join(err), file=sys.stderr)