File: ptyserv.py

package info (click to toggle)
twisted 25.5.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,560 kB
  • sloc: python: 203,171; makefile: 200; sh: 92; javascript: 36; xml: 31
file content (56 lines) | stat: -rw-r--r-- 1,309 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Copyright (c) Twisted Matrix Laboratories
# See LICENSE for details

"""
A PTY server that spawns a shell upon connection.

Run this example by typing in:
> python ptyserv.py

Telnet to the server once you start it by typing in: 
> telnet localhost 5823
"""

from twisted.internet import protocol, reactor


class FakeTelnet(protocol.Protocol):
    commandToRun = ["/bin/sh"]  # could have args too
    dirToRunIn = "/tmp"

    def connectionMade(self):
        print("connection made")
        self.propro = ProcessProtocol(self)
        reactor.spawnProcess(
            self.propro,
            self.commandToRun[0],
            self.commandToRun,
            {},
            self.dirToRunIn,
            usePTY=1,
        )

    def dataReceived(self, data):
        self.propro.transport.write(data)

    def connectionLost(self, reason):
        print("connection lost")
        self.propro.tranport.loseConnection()


class ProcessProtocol(protocol.ProcessProtocol):
    def __init__(self, pr):
        self.pr = pr

    def outReceived(self, data):
        self.pr.transport.write(data)

    def processEnded(self, reason):
        print("protocol connection lost")
        self.pr.transport.loseConnection()


f = protocol.Factory()
f.protocol = FakeTelnet
reactor.listenTCP(5823, f)
reactor.run()