• 主页
  • 如何在远程shell环境下对pdb进行stdin/stdout重定向?

如何在远程shell环境下对pdb进行stdin/stdout重定向?

我正在编写一个web shell,在服务器端使用ptpython、gevent和Flask,在客户端使用xtermjs和websockets。

我希望使用pdb来使用Python的普通breakpoint()函数。

我很高兴地发现Pdb类接受自定义的stdinstdout,但是我无法让它工作:(

在web shell中,用户输入的内容通过websocket进入服务器进程:有一个监听的greenlet,它写入由ptpython读取的管道。然后,通过websocket发送ptpython输出。到目前为止,它运行得很好。

现在使用pdb:多亏了sys.breakpointhook,我创建了一个自定义的Pdb实例,其中标准输入是一个管道,标准输出是另一个管道。我谨慎地使用gevent.fileobject.FileObjectPosix来获得非阻塞、协作的I/O流。我负责让用户输入写入到输入管道,我希望输出到另一个管道,这样我就可以将其重定向到代码中适当的“标准输出”处理例程。

但是,在收到与pdb提示符对应的第一条消息后,我被卡住了,似乎所有东西都被阻止了。

我用下面的代码重现了我的行为,任何帮助都将不胜感激:

from pdb import Pdb as _Pdb
import gevent
from gevent.fileobject import FileObjectPosix as File
import io
import os
import sys
import socket

debugger = None


class GeventPdb(_Pdb):
    def __init__(self, own_stdout):
        self._stdout = own_stdout
        r1, w1 = os.pipe()
        r2, w2 = os.pipe()
        self.r = File(r1)
        self.w = File(w1, "w")
        self.r2 = File(r2)
        self.w2 = File(w2, "w")
        super().__init__(stdin=self.r, stdout=self.w2)
        self.stdout_handling = gevent.spawn(self.handle_stdout)

    def send_text(self, txt):
        # this should write to the 'stdin' pipe,
        # thus provoking input reading from Pdb
        print("WRITING TO PDB's STDIN")
        self.w.write(txt.decode())

    def handle_stdout(self):
        # this should read what is written by Pdb
        # to Pdb's stdout, to redirect it to our
        # own stdout
        while True:
            print("BEFORE READING PDB's STDOUT")
            char = self.r2.read(1)
            print(f"WRITING TO CUSTOM STDOUT, stdout len is {len(self._stdout.getvalue())}")
            self._stdout.write(char)

def test_func():
    debugger.set_trace()

if __name__ == '__main__':
    custom_stdout = io.StringIO() # this simulates a custom stdout pipe
    debugger = GeventPdb(custom_stdout)

    # the next socket is the server socket,
    # for 'remote' operation
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('', 4444))
    s.listen(1)

    print("Connect client to continue... The client is used to send commands to the debugger")
    client, client_addr = s.accept()

    def handle_client(client):
      while True:
        cmd = client.recv(1024)
        if not cmd:
            break
        print("SENDING TEXT TO DEBUGGER...")
        debugger.send_text(cmd)

    gevent.spawn(handle_client, client)

    print("now start a function which starts the debugger...")
    print("we should see the pdb prompt")
    test_func()

我运行了以下代码,然后通过telnet localhost 4444连接,然后我可以看到收到pdb提示符,然后我可以输入命令并按enter键:在pdb的输入管道上似乎没有收到任何东西。它阻塞了。

任何帮助都将不胜感激!

转载请注明出处:http://www.jxbyjx.net/article/20230525/1887665.html