📜 ⬆️ ⬇️

Instant message from console to jabber

xmpp logo Often, system administrators are faced with the task of notifying themselves and colleagues of any events on the server, be it a report of successful ssh logins, a dramatically increased load, a drop in service, a message about switching to backup power or a boiling kettle.
Most often, this problem is solved, for example, by sending an e-mail message. But it is impossible to guarantee that the message, firstly, will arrive on time, and secondly, that it will be read immediately. Then, the administrator will think, we will use IM. But how? For example, keep centerim constantly open in screen? Agree, not the rainbow option.
The chip and the open protocol XMPP are in a hurry to rescue us. Many extensions to popular languages ​​and code examples have been written, allowing you to send a message to whom you need and send it quickly.
I will give an example of such a code.

When I needed this functionality, I ran through existing solutions in popular languages ​​such as C, php, perl, python. Some assumed the use of ready-made classes, some - the loading of modules. The code was monstrously cumbersome and unreadable, and I was looking for an elegant solution. And it was found in Python.

So, let's agree that we work in Linux. In fact, the script will probably work in Windows, but I did not ask myself for this purpose. We will need, in fact, python itself, as well as two modules - any dns and xmpppy , which is represented in Debian by the python-xmpp package.

The script code looks like this:
')
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import xmpp,sys

xmpp_jid = 'noreply@some.jabber.server'
xmpp_pwd = 'noreplypass'

to = sys.argv[1]
msg = sys.argv[2]

jid = xmpp.protocol.JID(xmpp_jid)
client = xmpp.Client(jid.getDomain(),debug=[])
client.connect()
client.auth(jid.getNode(),str(xmpp_pwd),resource='xmpppy')
client.send(xmpp.protocol.Message(to,msg))
client.disconnect()


The script, using the JID and password transmitted to it, logs in to the server, sends a message and closes the connection. There is simply no place. You will need to make a separate account for the script (but you can not do it, jabber allows multiple simultaneous connections with different resources) and enter the credentials into the variables xmpp_jid and xmpp_pwd .

Save the code to a file, make it executable, run it. The launch is as follows:

/home/username/scripts/send_xmpp_message username@email.server.ru ", , "


The flight of fantasy is unlimited: after a light modification, for example, you can redirect data to the script instead of passing arguments, and using crontab, send messages on a schedule.

Source: https://habr.com/ru/post/85407/


All Articles