2016-02-13 87 views
0

我在我的python腳本中使用plink.exe向路由器發送命令。我在「輸出」中找回結果。一個命令觸發路由器自己運行一系列命令。有沒有什麼方法可以在所有命令完成之前連續獲取輸出。我只將前幾行返回到輸出中。plink - 獲取連續輸出

comm = "plink.exe -pw admin [email protected] COMMAND" 
b = sub.Popen(comm,stdout=sub.PIPE,stderr=sub.PIPE) 
output, errors = b.communicate() 

print output 

我希望這對任何人都有用。 =)

回答

0

我找到了解決我的問題。 Paramiko模塊爲我工作。 =)

import sys 
import time 
import paramiko 

host = '192.168.1.1' 
user = 'admin' 
pwd = 'admin' 
i = 1 

#def interactive_shell(): 
ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 

transport = paramiko.Transport((host,22)) 
transport.connect(username=user, password=pwd) 
time.sleep(0.2) 
#chan = paramiko.transport.open_session() 
chan = transport.open_session() 
chan.setblocking(0) 
chan.invoke_shell() 
chan.send("command") # Send command to device 
chan.send("\n") # Send Enter 
time.sleep(1) #optional 
while not chan.exit_status_ready(): 
    time.sleep(0.1) 
    if chan.recv_ready() : 
     output = chan.recv(8192) 
     if len(output) > 0 : 
      outputLines = output.splitlines(True) 
      sys.stdout.write(output) 

     if "unit" in output: 
      sys.stdout.flush() 
      break 

    if chan.recv_stderr_ready() : 
     mystderr = chan.recv_stderr(8192) 
     if len(mystderr) > 0 : 
      print mystderr, "," 

transport.close()