title: How do I drop a bash shell from within Python?
body: <p>i'm working on a python tcp shell; I'd like to be able to telnet to a port, and have it prompt me with a shell: ex. </p>
  
  <pre><code>$ telnet localhost 5555
  Connected to localhost.
  Escape character is '^]'.
  $
  </code></pre>
  
  <p>The answer below was quite helpful in getting me on my way. Here's the working code. </p>
  
  <pre><code>import SocketServer, os, subprocess
  class EchoRequestHandler(SocketServer.BaseRequestHandler ):
      def setup(self):
          print self.client_address, 'connected!'
          self.request.send(str(self.client_address) + '\n')
          self.request.send(os.system('sh'))
      def handle(self):
          data = 'dummy'
          while data:
              data = self.request.recv(1024)
              self.request.send(os.popen(data.strip()).read())
              if data.strip() == 'bye':
                  return
  
      def finish(self):
          print self.client_address, 'disconnected!'
          self.request.send('bye ' + str(self.client_address) + '\n')
  
  server = SocketServer.ThreadingTCPServer(('', 7784), EchoRequestHandler)
  server.serve_forever()
  </code></pre>