shell Python中基于Twisted的简单管理应用程序挂起并且不发送数据

u7up0aaq  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(80)

我正在尝试编写一个简单的管理应用程序,它可以让我通过telnet访问计算机 shell (这只是Py0thon编程实践的测试)。当我连接到我的服务器,然后我只有黑屏在终端(Windows telnet客户端),但在我的程序日志有从子进程的输出,它没有得到发送到客户端。
我在Google上搜索了很多解决方案,但没有一个能正确地使用Twistedlib,结果也是一样的
我的服务器代码:

# -*- coding: utf-8 -*-

from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue # Python 2

from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
import sys

log = 'log.tmp'

def reader(pipe, queue):
    try:
        with pipe:
            for line in iter(pipe.readline, b''):
                queue.put((pipe, line))
    finally:
        queue.put(None)

class Server(LineReceiver):
    
    def connectionMade(self):
        self.sendLine("Creating shell...")
        self.shell = Popen("cmd.exe", stdout=PIPE, stderr=PIPE, bufsize=1, shell=True)
        q = Queue()
        Thread(target=reader, args=[self.shell.stdout, q]).start()
        Thread(target=reader, args=[self.shell.stderr, q]).start()
        for _ in xrange(2):
            for pipe, line in iter(q.get, b''):
                if pipe == self.shell.stdout:
                    sys.stdout.write(line)
                else:
                    sys.stderr.write(line)
        self.sendLine("Shell created!")
            
    def lineReceived(self, line):
        print line
        #stdout_data = self.shell.communicate(line)[0]
        self.sendLine(line)
    

if __name__ == "__main__":      
    ServerFactory = Factory.forProtocol(Server)
    
    reactor.listenTCP(8123, ServerFactory) #@UndefinedVariable
    reactor.run() #@UndefinedVariable

字符串

7y4bm7vi

7y4bm7vi1#

你把阻塞程序和非阻塞程序混在一起了。非阻塞部分不能运行,因为阻塞部分阻塞了。阻塞部分不工作,因为它们依赖于非阻塞部分的运行。
去掉PopenQueueThread,改用reactor.spawnProcess。或者摆脱Twisted,使用更多的线程进行联网。

相关问题