3
"""A multi-threaded telnet-like server that gives a Python prompt.
5
This is really a prototype for the same thing in C.
9
For security reasons, it only accepts requests from the current host.
10
This can still be insecure, but restricts violations from people who
11
can log in on your machine. Use with caution!
15
import sys, os, string, getopt, _thread, socket, traceback
17
PORT = 4000 # Default port
21
opts, args = getopt.getopt(sys.argv[1:], "")
23
raise getopt.error("Too many arguments.")
24
except getopt.error as msg:
30
port = string.atoi(args[0])
31
except ValueError as msg:
38
sys.stdout = sys.stderr
41
print("\n", __doc__, end=' ')
44
def main_thread(port):
45
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
48
print("Listening on port", port, "...")
50
(conn, addr) = sock.accept()
51
if addr[0] != conn.getsockname()[0]:
53
print("Refusing connection from non-local host", addr[0], ".")
55
_thread.start_new_thread(service_thread, (conn, addr))
58
def service_thread(conn, addr):
60
print("Thread %s has connection from %s.\n" % (str(_thread.get_ident()),
62
stdin = conn.makefile("r")
63
stdout = conn.makefile("w", 0)
64
run_interpreter(stdin, stdout)
65
print("Thread %s is done.\n" % str(_thread.get_ident()), end=' ')
67
def run_interpreter(stdin, stdout):
76
line = stdin.readline()
77
if line[:2] == '\377\354':
79
if not line and not source:
81
if line[-2:] == '\r\n':
82
line = line[:-2] + '\n'
83
source = source + line
85
code = compile_command(source)
86
except SyntaxError as err:
88
traceback.print_exception(SyntaxError, err, None, file=stdout)
94
run_command(code, stdin, stdout, globals)
95
except SystemExit as how:
101
stdout.write("Exit %s\n" % how)
103
stdout.write("\nGoodbye.\n")
105
def run_command(code, stdin, stdout, globals):
106
save = sys.stdin, sys.stdout, sys.stderr
108
sys.stdout = sys.stderr = stdout
112
except SystemExit as how:
113
raise SystemExit(how).with_traceback(sys.exc_info()[2])
115
type, value, tb = sys.exc_info()
116
if tb: tb = tb.tb_next
117
traceback.print_exception(type, value, tb)
120
sys.stdin, sys.stdout, sys.stderr = save
122
from code import compile_command