2017-07-29 17 views
0

您好,我正在嘗試編寫一個簡單的管理應用程序,它使我能夠訪問計算機shell tr​​ought telnet(這只是測試python編程實踐)當我連接到我的服務器,然後我只在終端(Windows遠程登錄客戶端)黑屏,但在我的程序日誌有輸出形式的子進程,它sdoes沒有被髮送到客戶端 我已經搜索了谷歌的許多解決方案,但沒有一個工作與扭曲的LIB適當,結果是一樣的基於Twisted的簡單管理應用程序掛起並且不發送數據

我的服務器代碼:

# -*- 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 

回答

0

您將阻塞程序與非阻塞程序混合使用。由於阻塞部件阻塞,非阻塞部件無法運行。阻塞部件不工作,因爲它們依賴於運行的非阻塞部件。

擺脫PopenQueueThread並使用reactor.spawnProcess來代替。或者擺脫扭曲並使用更多線程進行聯網。

相關問題