I'm making a lightweight manhole-like remote interactive Python shell by setting stdin
, stdout
, stderr
to a socket and then calling code.interact()
.
This works beautifully except for arrow keys showing up like ^[[C
when I connect to it via nc localhost 1337
.
It's not an issue of not having readline
installed, as that works fine when I launch the interpreter manually, even if I run code.interact()
. The issue only occurs through sockets. I can import readline
inside my remote shell but that does nothing.
Perhaps I'm missing something related to readline
in SocketWrapper.read()
?
import socket
import sys
import readline
readline.parse_and_bind('tab: complete') # doesn't work
import code
port = 1337
while True:
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', port))
sock.listen(1)
print("~Listening on port %d~" % port)
connection, connection_addr = sock.accept()
print("Accepted connection from %s." % (connection_addr,))
class SocketWrapper:
def __init__(self, sock):
self.sock = sock
def read(self, length):
return self.sock.recv(length)
def write(self, text):
return self.sock.send(text)
def readline(self):
return self.sock.makefile().readline()
sockfile = SocketWrapper(connection)
sys.stdin = sockfile
sys.stdout = sockfile
sys.stderr = sockfile
code.interact(
local=dict(globals(), **locals())
)