Created
September 2, 2014 20:05
-
-
Save ioggstream/23586e0e69f210f61008 to your computer and use it in GitHub Desktop.
omprog-twisted-sample.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Copyright (c) Twisted Matrix Laboratories. | |
# See LICENSE for details. | |
""" | |
Example using stdio, LineReceiver, ClientFactory and twisted.web.client. | |
This could be used with rsyslog omprog module to forward messages to | |
different servers | |
cat >> /etc/rsyslog.d/omprog-python.conf <<EOF | |
Module (load="omprog") | |
*.* action(type="omprog" | |
binary="/pathto/omprog-twisted-sample.py" | |
template="RSYSLOG_TraditionalFileFormat") | |
EOF | |
Note that the WebCheckerCommandProtocol protocol could easily be used in e.g. | |
a telnet server instead; see the comments for details. | |
Based on an example by Abe Fettig. | |
""" | |
from twisted.internet import reactor, defer, endpoints | |
from twisted.internet import stdio, reactor, protocol | |
from twisted.protocols import basic | |
from twisted.web import client | |
class EchoClient(protocol.Protocol): | |
"""Once connected, send a message, then print the result.""" | |
def connectionMade(self): | |
self.transport.write("Joining logserver") | |
def dataReceived(self, data): | |
"shouldn't receive data from server" | |
pass | |
def connectionLost(self, reason): | |
print "connection lost" | |
def sendMessage(self, msg): | |
self.transport.write("MESSAGE %s\n" % msg) | |
class EchoFactory(protocol.ClientFactory): | |
protocol = EchoClient | |
def clientConnectionFailed(self, connector, reason): | |
print "Connection failed - goodbye!" | |
reactor.stop() | |
def clientConnectionLost(self, connector, reason): | |
print "Connection lost - goodbye!" | |
reactor.stop() | |
class WebCheckerCommandProtocol(basic.LineReceiver): | |
"""Forwards received messages to a given server""" | |
delimiter = '\n' # unix terminal style newlines. remove this line | |
# for use with Telnet | |
def connectionMade(self): | |
self.sendLine("Web checker console. Type 'help' for help.") | |
def lineReceived(self, line): | |
# Ignore blank lines | |
if not line: return | |
if not getattr(self,'connector',None): | |
self.connector = reactor.connectTCP('127.0.0.1', 8000, EchoFactory()) | |
self.sendLine('Sending line: ' + str(line)) | |
self.connector.transport.write(line + self.delimiter) | |
print('%r' % 'done') | |
def connectionLost(self, reason): | |
# stop the reactor, only because this is meant to be run in Stdio. | |
reactor.stop() | |
if __name__ == "__main__": | |
stdio.StandardIO(WebCheckerCommandProtocol()) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment