| 1 |
# Copyright (c) Twisted Matrix Laboratories |
| 2 |
# See LICENSE for details |
| 3 |
|
| 4 |
""" |
| 5 |
A PTY server that spawns a shell upon connection. |
| 6 |
|
| 7 |
Run this example by typing in: |
| 8 |
> python ptyserv.py |
| 9 |
|
| 10 |
Telnet to the server once you start it by typing in: |
| 11 |
> telnet localhost 5823 |
| 12 |
""" |
| 13 |
|
| 14 |
from twisted.internet import protocol, reactor |
| 15 |
|
| 16 |
|
| 17 |
class FakeTelnet(protocol.Protocol): |
| 18 |
commandToRun = ["/bin/sh"] # could have args too |
| 19 |
dirToRunIn = "/tmp" |
| 20 |
|
| 21 |
def connectionMade(self): |
| 22 |
print("connection made") |
| 23 |
self.propro = ProcessProtocol(self) |
| 24 |
reactor.spawnProcess( |
| 25 |
self.propro, |
| 26 |
self.commandToRun[0], |
| 27 |
self.commandToRun, |
| 28 |
{}, |
| 29 |
self.dirToRunIn, |
| 30 |
usePTY=1, |
| 31 |
) |
| 32 |
|
| 33 |
def dataReceived(self, data): |
| 34 |
self.propro.transport.write(data) |
| 35 |
|
| 36 |
def connectionLost(self, reason): |
| 37 |
print("connection lost") |
| 38 |
self.propro.tranport.loseConnection() |
| 39 |
|
| 40 |
|
| 41 |
class ProcessProtocol(protocol.ProcessProtocol): |
| 42 |
def __init__(self, pr): |
| 43 |
self.pr = pr |
| 44 |
|
| 45 |
def outReceived(self, data): |
| 46 |
self.pr.transport.write(data) |
| 47 |
|
| 48 |
def processEnded(self, reason): |
| 49 |
print("protocol connection lost") |
| 50 |
self.pr.transport.loseConnection() |
| 51 |
|
| 52 |
|
| 53 |
f = protocol.Factory() |
| 54 |
f.protocol = FakeTelnet |
| 55 |
reactor.listenTCP(5823, f) |
| 56 |
reactor.run() |