Imported Upstream version 12.1.0
[contrib/python-twisted.git] / doc / core / examples / ptyserv.py
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 reactor, protocol
15
16 class FakeTelnet(protocol.Protocol):
17     commandToRun = ['/bin/sh'] # could have args too
18     dirToRunIn = '/tmp'
19     def connectionMade(self):
20         print 'connection made'
21         self.propro = ProcessProtocol(self)
22         reactor.spawnProcess(self.propro, self.commandToRun[0], self.commandToRun, {},
23                              self.dirToRunIn, usePTY=1)
24     def dataReceived(self, data):
25         self.propro.transport.write(data)
26     def conectionLost(self):
27         print 'connection lost'
28         self.propro.tranport.loseConnection()
29
30 class ProcessProtocol(protocol.ProcessProtocol):
31
32     def __init__(self, pr):
33         self.pr = pr
34
35     def outReceived(self, data):
36         self.pr.transport.write(data)
37     
38     def processEnded(self, reason):
39         print 'protocol conection lost'
40         self.pr.transport.loseConnection()
41
42 f = protocol.Factory()
43 f.protocol = FakeTelnet
44 reactor.listenTCP(5823, f)
45 reactor.run()