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