/Demo/sockets/rpythond.py

http://unladen-swallow.googlecode.com/ · Python · 52 lines · 41 code · 6 blank · 5 comment · 8 complexity · 4ae1762958ecbbcf82c5f72ef9721674 MD5 · raw file

  1. #! /usr/bin/env python
  2. # Remote python server.
  3. # Execute Python commands remotely and send output back.
  4. # WARNING: This version has a gaping security hole -- it accepts requests
  5. # from any host on the Internet!
  6. import sys
  7. from socket import *
  8. import StringIO
  9. import traceback
  10. PORT = 4127
  11. BUFSIZE = 1024
  12. def main():
  13. if len(sys.argv) > 1:
  14. port = int(eval(sys.argv[1]))
  15. else:
  16. port = PORT
  17. s = socket(AF_INET, SOCK_STREAM)
  18. s.bind(('', port))
  19. s.listen(1)
  20. while 1:
  21. conn, (remotehost, remoteport) = s.accept()
  22. print 'connected by', remotehost, remoteport
  23. request = ''
  24. while 1:
  25. data = conn.recv(BUFSIZE)
  26. if not data:
  27. break
  28. request = request + data
  29. reply = execute(request)
  30. conn.send(reply)
  31. conn.close()
  32. def execute(request):
  33. stdout = sys.stdout
  34. stderr = sys.stderr
  35. sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
  36. try:
  37. try:
  38. exec request in {}, {}
  39. except:
  40. print
  41. traceback.print_exc(100)
  42. finally:
  43. sys.stderr = stderr
  44. sys.stdout = stdout
  45. return fakefile.getvalue()
  46. main()