1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
5 """Telnet-based shell."""
8 from twisted.protocols import telnet
9 from twisted.internet import protocol
10 from twisted.python import log, failure
13 import string, copy, sys
14 from cStringIO import StringIO
17 class Shell(telnet.Telnet):
18 """A Python command-line shell."""
20 def connectionMade(self):
21 telnet.Telnet.connectionMade(self)
25 self.transport.write(">>> ")
27 def checkUserAndPass(self, username, password):
28 return ((self.factory.username == username) and (password == self.factory.password))
30 def write(self, data):
31 """Write some data to the transport.
33 self.transport.write(data)
35 def telnet_Command(self, cmd):
38 cmd = string.join(self.lineBuffer, '\n') + '\n\n\n'
43 self.lineBuffer.append(cmd)
44 self.transport.write("... ")
50 def doCommand(self, cmd):
52 # TODO -- refactor this, Reality.author.Author, and the manhole shell
53 #to use common functionality (perhaps a twisted.python.code module?)
60 code = compile(cmd,fn,'eval')
61 result = eval(code, self.factory.namespace)
64 code = compile(cmd, fn, 'exec')
65 exec code in self.factory.namespace
66 except SyntaxError, e:
67 if not self.lineBuffer and str(e)[:14] == "unexpected EOF":
68 self.lineBuffer.append(cmd)
69 self.transport.write("... ")
72 failure.Failure().printTraceback(file=self)
74 self.write('\r\n>>> ')
78 failure.Failure().printTraceback(file=self)
80 self.write('\r\n>>> ')
85 self.factory.namespace['_'] = result
86 if result is not None:
87 self.transport.write(repr(result))
88 self.transport.write('\r\n')
89 self.transport.write(">>> ")
93 class ShellFactory(protocol.Factory):
106 def setService(self, service):
107 self.namespace['service'] = self.service = service
109 def __getstate__(self):
110 """This returns the persistent state of this shell factory.
113 ns = copy.copy(dict['namespace'])
114 dict['namespace'] = ns
115 if ns.has_key('__builtins__'):
116 del ns['__builtins__']