shell.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #! /usr/bin/env python
  2. """
  3. a remote python shell
  4. for injection into startserver.py
  5. """
  6. import sys
  7. import os
  8. import socket
  9. import select
  10. from traceback import print_exc
  11. from threading import Thread
  12. def clientside():
  13. print("client side starting")
  14. host, port = sys.argv[1].split(':')
  15. port = int(port)
  16. myself = open(os.path.abspath(sys.argv[0]), 'rU').read()
  17. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  18. sock.connect((host, port))
  19. sock.sendall(repr(myself)+'\n')
  20. print("send boot string")
  21. inputlist = [sock, sys.stdin]
  22. try:
  23. while 1:
  24. r, w, e = select.select(inputlist, [], [])
  25. if sys.stdin in r:
  26. line = raw_input()
  27. sock.sendall(line + '\n')
  28. if sock in r:
  29. line = sock.recv(4096)
  30. sys.stdout.write(line)
  31. sys.stdout.flush()
  32. except:
  33. import traceback
  34. print(traceback.print_exc())
  35. sys.exit(1)
  36. class promptagent(Thread):
  37. def __init__(self, clientsock):
  38. print("server side starting")
  39. Thread.__init__(self)
  40. self.clientsock = clientsock
  41. def run(self):
  42. print("Entering thread prompt loop")
  43. clientfile = self.clientsock.makefile('w')
  44. filein = self.clientsock.makefile('r')
  45. loc = self.clientsock.getsockname()
  46. while 1:
  47. try:
  48. clientfile.write('%s %s >>> ' % loc)
  49. clientfile.flush()
  50. line = filein.readline()
  51. if not line:
  52. raise EOFError("nothing")
  53. if line.strip():
  54. oldout, olderr = sys.stdout, sys.stderr
  55. sys.stdout, sys.stderr = clientfile, clientfile
  56. try:
  57. try:
  58. exec(compile(line + '\n',
  59. '<remote pyin>', 'single'))
  60. except:
  61. print_exc()
  62. finally:
  63. sys.stdout = oldout
  64. sys.stderr = olderr
  65. clientfile.flush()
  66. except EOFError:
  67. sys.stderr.write("connection close, prompt thread returns")
  68. break
  69. self.clientsock.close()
  70. sock = globals().get('clientsock')
  71. if sock is not None:
  72. prompter = promptagent(sock)
  73. prompter.start()
  74. print("promptagent - thread started")
  75. else:
  76. clientside()