I have written a sshdaemon based on the twisted sshsimpleserver.py which works great.
http://twistedmatrix.com/documents/current/conch/examples/
But I now want to pass a command line argument to the EchoProtocol, to change it's behaviour depending on the argument. How can I do this? In this case I would like to pass the 'options.test' parameter to my protocol.
[...]
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-p', '--port', action = 'store', type = 'int',
dest = 'port', default = 1235, help = 'server port')
parser.add_option('-t', '--test', action = 'store', type =
'string', dest = 'test', default = '123')
(options, args) = parser.parse_args()
components.registerAdapter(ExampleSession, ExampleAvatar,
session.ISession)
[...]
reactor.listenTCP(options.port, ExampleFactory())
reactor.run()
Since the session instance is created by the factory, I can't seem to be able to pass additional args to neither the session constructor nor the protocol. I already tried to make the options name global but it is not visible in the protocol context/scope.
Btw. I moved the protocol class into it's own file and import it in the main file.
You can create you own Factory and pass parameters to it. See an example from the docs
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
# self.factory was set by the factory's default buildProtocol:
self.transport.write(self.factory.quote + '\r\n')
self.transport.loseConnection()
class QOTDFactory(Factory):
# This will be used by the default buildProtocol to create new protocols:
protocol = QOTD
def __init__(self, quote=None):
self.quote = quote or 'An apple a day keeps the doctor away'
endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))
reactor.run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With