rpythond.py 1.3 KB

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