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