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

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

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

  1. # -*- coding: utf-8 -*-
  2. from subprocess import Popen, PIPE
  3. from threading import Thread
  4. from Queue import Queue # Python 2
  5. from twisted.internet import reactor
  6. from twisted.internet.protocol import Factory
  7. from twisted.protocols.basic import LineReceiver
  8. import sys
  9. log = 'log.tmp'
  10. def reader(pipe, queue):
  11. try:
  12. with pipe:
  13. for line in iter(pipe.readline, b''):
  14. queue.put((pipe, line))
  15. finally:
  16. queue.put(None)
  17. class Server(LineReceiver):
  18. def connectionMade(self):
  19. self.sendLine("Creating shell...")
  20. self.shell = Popen("cmd.exe", stdout=PIPE, stderr=PIPE, bufsize=1, shell=True)
  21. q = Queue()
  22. Thread(target=reader, args=[self.shell.stdout, q]).start()
  23. Thread(target=reader, args=[self.shell.stderr, q]).start()
  24. for _ in xrange(2):
  25. for pipe, line in iter(q.get, b''):
  26. if pipe == self.shell.stdout:
  27. sys.stdout.write(line)
  28. else:
  29. sys.stderr.write(line)
  30. self.sendLine("Shell created!")
  31. def lineReceived(self, line):
  32. print line
  33. #stdout_data = self.shell.communicate(line)[0]
  34. self.sendLine(line)
  35. if __name__ == "__main__":
  36. ServerFactory = Factory.forProtocol(Server)
  37. reactor.listenTCP(8123, ServerFactory) #@UndefinedVariable
  38. reactor.run() #@UndefinedVariable

字符串

7y4bm7vi

7y4bm7vi1#

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

相关问题