1#!/usr/bin/env python3
2
3"""
4Remote python server.
5Execute Python commands remotely and send output back.
6
7WARNING: This version has a gaping security hole -- it accepts requests
8from any host on the Internet!
9"""
10
11import sys
12from socket import socket, AF_INET, SOCK_STREAM
13import io
14import traceback
15
16PORT = 4127
17BUFSIZE = 1024
18
19def 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        with conn:
30            print('connection from', remotehost, remoteport)
31            request = b''
32            while True:
33                data = conn.recv(BUFSIZE)
34                if not data:
35                    break
36                request += data
37            reply = execute(request.decode())
38            conn.send(reply.encode())
39
40def 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
55try:
56    main()
57except KeyboardInterrupt:
58    pass
59