~soren/nova/iptables-security-groups

« back to all changes in this revision

Viewing changes to vendor/Twisted-10.0.0/doc/conch/examples/demo_insults.tac

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
 
2
# See LICENSE for details.
 
3
 
 
4
# You can run this .tac file directly with:
 
5
#    twistd -ny demo_insults.tac
 
6
 
 
7
"""Various simple terminal manipulations using the insults module.
 
8
 
 
9
This demo sets up two listening ports: one on 6022 which accepts ssh
 
10
connections; one on 6023 which accepts telnet connections.  No login
 
11
for the telnet server is required; for the ssh server, \"username\" is
 
12
the username and \"password\" is the password.
 
13
 
 
14
The TerminalProtocol subclass defined here ignores most user input
 
15
(except to print it out to the server log) and spends the duration of
 
16
the connection drawing (the author's humble approximation of)
 
17
raindrops at random locations on the client's terminal.  +, -, *, and
 
18
/ are respected and each adjusts an aspect of the timing of the
 
19
animation process.
 
20
"""
 
21
 
 
22
import random, string
 
23
 
 
24
from twisted.python import log
 
25
from twisted.internet import protocol, task
 
26
from twisted.application import internet, service
 
27
from twisted.cred import checkers, portal
 
28
 
 
29
from twisted.conch.insults import insults
 
30
from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
 
31
from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
 
32
 
 
33
class DrawingFinished(Exception):
 
34
    """Sentinel exception, raised when no \"frames\" for a particular
 
35
    \"animation\" remain to be drawn.
 
36
    """
 
37
 
 
38
class Drawable:
 
39
    """Representation of an animation.
 
40
 
 
41
    Constructed with a protocol instance and a coordinate on the
 
42
    screen, waits for invocations of iterate() at which point it
 
43
    erases the previous frame of the animation and draws the next one,
 
44
    using its protocol instance and always placing the upper left hand
 
45
    corner of the frame at the given coordinates.
 
46
 
 
47
    Frames are defined with draw_ prefixed methods.  Erasure is
 
48
    performed by erase_ prefixed methods.
 
49
    """
 
50
    n = 0
 
51
 
 
52
    def __init__(self, proto, col, line):
 
53
        self.proto = proto
 
54
        self.col = col
 
55
        self.line = line
 
56
 
 
57
    def drawLines(self, s):
 
58
        lines = s.splitlines()
 
59
        c = self.col
 
60
        line = self.line
 
61
        for l in lines:
 
62
            self.proto.cursorPosition(c - len(lines) / 2, line)
 
63
            self.proto.write(l)
 
64
            line += 1
 
65
 
 
66
    def iterate(self):
 
67
        getattr(self, 'erase_' + str(self.n))()
 
68
        self.n += 1
 
69
        f = getattr(self, 'draw_' + str(self.n), None)
 
70
        if f is None:
 
71
            raise DrawingFinished()
 
72
        f()
 
73
 
 
74
    def erase_0(self):
 
75
        pass
 
76
 
 
77
 
 
78
class Splat(Drawable):
 
79
    HEIGHT = 5
 
80
    WIDTH = 11
 
81
 
 
82
    def draw_1(self):
 
83
        # . .
 
84
        #. . .
 
85
        # . .
 
86
        self.drawLines(' . .\n. . .\n . .')
 
87
 
 
88
    def erase_1(self):
 
89
        self.drawLines('    \n     \n    ')
 
90
 
 
91
    def draw_2(self):
 
92
        #  . . . .
 
93
        # . o o o .
 
94
        #. o o o o .
 
95
        # . o o o .
 
96
        #  . . . .
 
97
        self.drawLines('  . . . .\n . o o o .\n. o o o o .\n . o o o .\n  . . . .')
 
98
 
 
99
    def erase_2(self):
 
100
        self.drawLines('         \n          \n           \n          \n         ')
 
101
 
 
102
    def draw_3(self):
 
103
        #  o o o o
 
104
        # o O O O o
 
105
        #o O O O O o
 
106
        # o O O O o
 
107
        #  o o o o
 
108
        self.drawLines('  o o o o\n o O O O o\no O O O O o\n o O O O o\n  o o o o')
 
109
 
 
110
    erase_3 = erase_2
 
111
 
 
112
    def draw_4(self):
 
113
        #  O O O O
 
114
        # O . . . O
 
115
        #O . . . . O
 
116
        # O . . . O
 
117
        #  O O O O
 
118
        self.drawLines('  O O O O\n O . . . O\nO . . . . O\n O . . . O\n  O O O O')
 
119
 
 
120
    erase_4 = erase_3
 
121
 
 
122
    def draw_5(self):
 
123
        #  . . . .
 
124
        # .       .
 
125
        #.         .
 
126
        # .       .
 
127
        #  . . . .
 
128
        self.drawLines('  . . . .\n .       .\n.         .\n .       .\n  . . . .')
 
129
 
 
130
    erase_5 = erase_4
 
131
 
 
132
class Drop(Drawable):
 
133
    WIDTH = 3
 
134
    HEIGHT = 4
 
135
 
 
136
    def draw_1(self):
 
137
        # o
 
138
        self.drawLines(' o')
 
139
 
 
140
    def erase_1(self):
 
141
        self.drawLines('  ')
 
142
 
 
143
    def draw_2(self):
 
144
        # _
 
145
        #/ \
 
146
        #\./
 
147
        self.drawLines(' _ \n/ \\\n\\./')
 
148
 
 
149
    def erase_2(self):
 
150
        self.drawLines('  \n   \n   ')
 
151
 
 
152
    def draw_3(self):
 
153
        # O
 
154
        self.drawLines(' O')
 
155
 
 
156
    def erase_3(self):
 
157
        self.drawLines('  ')
 
158
 
 
159
class DemoProtocol(insults.TerminalProtocol):
 
160
    """Draws random things at random places on the screen.
 
161
    """
 
162
    width = 80
 
163
    height = 24
 
164
 
 
165
    interval = 0.1
 
166
    rate = 0.05
 
167
 
 
168
    def connectionMade(self):
 
169
        self.run()
 
170
 
 
171
    def connectionLost(self, reason):
 
172
        self._call.stop()
 
173
        del self._call
 
174
 
 
175
    def run(self):
 
176
        # Clear the screen, matey
 
177
        self.terminal.eraseDisplay()
 
178
 
 
179
        self._call = task.LoopingCall(self._iterate)
 
180
        self._call.start(self.interval)
 
181
 
 
182
    def _iterate(self):
 
183
        cls = random.choice((Splat, Drop))
 
184
 
 
185
        # Move to a random location on the screen
 
186
        col = random.randrange(self.width - cls.WIDTH) + cls.WIDTH
 
187
        line = random.randrange(self.height - cls.HEIGHT) + cls.HEIGHT
 
188
 
 
189
        s = cls(self.terminal, col, line)
 
190
 
 
191
        c = task.LoopingCall(s.iterate)
 
192
        c.start(self.rate).addErrback(lambda f: f.trap(DrawingFinished)).addErrback(log.err)
 
193
 
 
194
    # ITerminalListener
 
195
    def terminalSize(self, width, height):
 
196
        self.width = width
 
197
        self.height = height
 
198
 
 
199
    def unhandledControlSequence(self, seq):
 
200
        log.msg("Client sent something weird: %r" % (seq,))
 
201
 
 
202
    def keystrokeReceived(self, keyID, modifier):
 
203
        if keyID == '+':
 
204
            self.interval /= 1.1
 
205
        elif keyID == '-':
 
206
            self.interval *= 1.1
 
207
        elif keyID == '*':
 
208
            self.rate /= 1.1
 
209
        elif keyID == '/':
 
210
            self.rate *= 1.1
 
211
        else:
 
212
            log.msg("Client sent: %r" % (keyID,))
 
213
            return
 
214
 
 
215
        self._call.stop()
 
216
        self._call = task.LoopingCall(self._iterate)
 
217
        self._call.start(self.interval)
 
218
 
 
219
 
 
220
def makeService(args):
 
221
    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
 
222
 
 
223
    f = protocol.ServerFactory()
 
224
    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
 
225
                                         insults.ServerProtocol,
 
226
                                         args['protocolFactory'],
 
227
                                         *args.get('protocolArgs', ()),
 
228
                                         **args.get('protocolKwArgs', {}))
 
229
    tsvc = internet.TCPServer(args['telnet'], f)
 
230
 
 
231
    def chainProtocolFactory():
 
232
        return insults.ServerProtocol(
 
233
            args['protocolFactory'],
 
234
            *args.get('protocolArgs', ()),
 
235
            **args.get('protocolKwArgs', {}))
 
236
 
 
237
    rlm = TerminalRealm()
 
238
    rlm.chainedProtocolFactory = chainProtocolFactory
 
239
    ptl = portal.Portal(rlm, [checker])
 
240
    f = ConchFactory(ptl)
 
241
    csvc = internet.TCPServer(args['ssh'], f)
 
242
 
 
243
    m = service.MultiService()
 
244
    tsvc.setServiceParent(m)
 
245
    csvc.setServiceParent(m)
 
246
    return m
 
247
 
 
248
application = service.Application("Insults Demo App")
 
249
 
 
250
makeService({'protocolFactory': DemoProtocol,
 
251
             'telnet': 6023,
 
252
             'ssh': 6022}).setServiceParent(application)