SleekXMPP-How to check whether the user is authenticated or not? - python

As the question says, how can I do it? following is the code-
import logging
from sleekxmpp import ClientXMPP
logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')
def on_session(event):
xmpp.get_roster()
xmpp = ClientXMPP(jid, password)
xmpp.add_event_handler('session_start', on_session)
if xmpp.connect():
print xmpp.authenticated # Always prints `False`
xmpp.process(block=True)
I can see that printing in the logs, but I rather want to check it in the code as well. How can I do it?

In XMPP, the authentication is handled by SASL which usually starts once the client is connected.
In your case, mere connection success doesn't imply that authentication was done. You need to put event handler for SASL authentication success and failure cases. Going through the sleekxmpp events, it makes me believe that it can be done by monitoring auth_success and failed_auth events. Possible code will be :
xmpp.add_event_handler("failed_auth", on_failed_auth)
xmpp.add_event_handler("auth_success", on_auth_success)

Related

How to write the events happening in controller to client var/log/messages in python?

I am trying to write a code where Failover events happening on the filer side should also be logged on client /var/log/messages.
For example, I will be having the following
1. filers
2. n number of clients(Linux, windows)
3. test will be run using one RHEL host which can access filers and clients.
I tried using the logger for Linux with the -n option which specifies the client_ip followed by the message which needs to be logged to var/log/messages. I didn't get the output.
My Question is
can we use the logger functionality where we can specify the client IP to log the messages
if I can use logger then can I define the message as a variable and when the event happens can I call the logger as messages have to be updated runtime.

Asynchronous Bidirectional RPC

I am looking for a RPC library in Java or Python (Python is preferred) that uses TCP. It should support:
Asynchronous
Bidirectional
RPC
Some sort of event loop (with callbacks or similar)
Any recommendations? I have looked a things like bjsonrpc which seemed to be the right sort of thing however it didn't seem possible for the server to identify which connections; so if a user has identified himself/herself and a request comes in from another user to send a message to that user it doesn't expose that users connection so we can send the message.
You should definitely check out Twisted. It's an event-based Python networking framework that has an implementation of an event loop (called the "reactor") supporting select, poll, epoll, kqueue and I/O completion ports, and mediates asynchronous calls with objects called Deferreds
As for your RPC requirement, perhaps you should check out Twisted's PB library or AMP.
I'm not entirely sure what you meanאt by "Event loop", but you should check out RPyC (Python)
RPyC Project page
i'm the author of bjsonrpc. I'm sure it's possible to do what you want with it.
Some things maybe are poorly documented or maybe some examples are needed.
But, in short, Handlers can store internal states (like authenticated or not, or maybe username). From any handler you can access the "Connection" class, which has the socket itself.
Seems you want something like a chat as an example. I did something similar in the past. I'll try to add a chat example for a new release.
Internal states are explained here:
http://packages.python.org/bjsonrpc/tutorial1/index.html#stateful-server
They should be used for authentication (but no standard auth method is provided yet).
On how to reach the connection class from the handler, that isn't documented yet (sorry), but it is used sometimes in the examples inside the source code. For example, example1-server.py contains this public function:
def gettotal(self):
self._conn.notify.notify("total")
return self.value_total
BaseHandler._conn represents the connection for that user. And is exactly the same class you get when you connect:
conn = bjsonrpc.connect(host=host,port=port,handler_factory=MyHandler)
So, you can store the connections for logged users in a global variable, and later call any client method you want to.
I am involved in developing Versile Python (VPy) which provides the capabilities you are requesting. It is currently available as development releases intended primarily for testing, however you may want to check it out.
Regarding identifying users you can configure remote methods to receive a context object which enables the method to receive information about an authenticated user, using a syntax similar to this draft code.
from versile.quick import *
#doc
class MessageBox(VExternal):
"""Dispatches IM messages."""
#publish(show=True, doc=True, ctx=True)
def send_message(self, msg, ctx=None):
"""Sends a message to the message box"""
if ctx.identity is None:
raise VException('No authenticated user')
else:
# do something ...
pass

twisted handle_quit() the way to disconnect?

so I'm implementing a log server with twisted (python-loggingserver) and I added simple authentication to the server. If the authentication fails, I wanna close the connection to the client. The class in the log server code already has a function called handle_quit(). Is that the right way to close the connection? Here's a code snippet:
if password != log_password:
self._logger.warning("Authentication failed. Connection closed.")
self.handle_quit()
If the handle_quit message you're referring to is this one, then that should work fine. The only thing the method does is self.transport.loseConnection(), which closes the connection. You could also just do self.transport.loseConnection() yourself, which will accomplish the same thing (since it is, of course, the same thing). I would select between these two options by thinking about whether failed authentication should just close the connection or if it should always be treated the same way a quit command is treated. In the current code this makes no difference, but you might imagine the quit command having extra processing at some future point (cleaning up some resources or something).

"NOTICE AUTH" notifications when connecting to IRC server

As a learning exercise, I'm writing a Python program to connect to a channel on an IRC network, so I can output messages in the channel to stdout. I'm using asynchat and manually sending the protocol messages, rather than using something like Twisted or existing bot code from the net - again, it's a more useful learning experience that way.
I can send JOIN and USER commands quite happily, and can PING/PONG away as required. However, I've noticed when opening a socket to port 6667, I'll receive some messages:
NOTICE AUTH :*** Looking up your hostname...
NOTICE AUTH :*** Checking ident
NOTICE AUTH :*** Found your hostname
NOTICE AUTH :*** No identd (auth) response
even if I've not yet sent the JOIN/USER commands.
So, is this opening sequence of notifications specified anywhere? As far as I can see, the RFC doesn't specify for anything in particular to happen before the client sends the JOIN command, and I wasn't sure whether to wait for receipt of these notices before sending the JOIN command, and if so how do I detect that I've received all of the notices?
There's no RFC requirement to do this, it's just a common thing that servers in the wild do. Observe that they're plain old NOTICE commands (i.e. just messages). Just treat them as messages sent to a psuedo-user "AUTH" (since the server doesn't have a better name for you yet). You're not required to wait for them, and the server is not required to send them.

Python logging SMTPHandler - handling offline SMTP server

I have setup the logging module for my new python script. I have two handlers, one sending stuff to a file, and one for email alerts. The SMTPHandler is setup to mail anything at the ERROR level or above.
Everything works great, unless the SMTP connection fails. If the SMTP server does not respond or authentication fails (it requires SMTP auth), then the whole script dies.
I am fairly new to python, so I am trying to figure out how to capture the exception that the SMTPHandler is raising so that any problems sending the log message via email won't bring down my entire script. Since I am also writing errors to a log file, if the SMTP alert fails, I just want to keep going, not halt anything.
If I need a "try:" statement, would it go around the logging.handlers.SMTPHandler setup, or around the individual calls to my_logger.error()?
Exceptions which occur during logging should not stop your script, though they may cause a traceback to be printed to sys.stderr. In order to prevent this printout, do the following:
logging.raiseExceptions = 0
This is not the default (because in development you typically want to know about failures) but in production, raiseExceptions should not be set.
You should find that the SMTPHandler will attempt a re-connection the next time an ERROR (or higher) is logged.
logging does pass through SystemExit and KeyboardInterrupt exceptions, but all others should be handled so that they do not cause termination of an application which uses logging. If you find that this is not the case, please post specific details of the exceptions which are getting through and causing your script to terminate, and about your version of Python/operating system. Bear in mind that the script may appear to hang if there is a network timeout which is causing the handler to block (e.g. if a DNS lookup takes a long time, or if the SMTP connection takes a long time).
You probably need to do both. To figure this out, I suggest to install a local mail server and use that. This way, you can shut it down while your script runs and note down the error message.
To keep the code maintainable, you should extends SMTPHandler in such a way that you can handle the exceptions in a single place (instead of wrapping every logger call with try-except).

Categories

Resources