2016-11-06 55 views
0

我想用paramiko遠程執行一些命令,但recv_ready()不會返回正確的值。
例如,在pwd \n命令後,它會持續報告通道尚未準備就緒(顯然爲false)。對於某些命令,它可以正常工作ls。 我在做什麼有什麼問題,或者paramiko有問題嗎?Paramiko recv_ready()返回假值

import paramiko 
import re 
import time 

def sudo_ssh(hostname, usernameIn, passIn, cmd): 

    # Create an SSH client 
    client = paramiko.SSHClient() 

    # Make sure that we add the remote server's SSH key automatically 
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 

    # Connect to the client 
    client.connect(hostname, username=usernameIn, password=passIn) 

    # Create a raw shell 
    channel = client.invoke_shell() 


    # Send the sudo command 
    for command in cmd: 
     print("CMD= " + command + "\n") 
     time.sleep(1) 

     # wait until channel is ready 
     while not channel.recv_ready() : 
      print("NOT READY " + str(channel.recv_ready()) + "\n \n") 
      time.sleep(1) 

     # Send the command 
     channel.send(command) 
     channel.send("\n") 

     # Wait a bit, if necessary 
     time.sleep(1) 

     # Flush the receive buffer 
     receive_buffer = channel.recv(4096) 

     # If promted send the sudo pass 
     if re.search(b".*\[sudo\].*", receive_buffer): 
      time.sleep(1) 
      print(" TYPING SUDO PASSWORD .... \n") 
      channel.send("sudoPass" + "\n") 
      receive_buffer = channel.recv(4096) 

     # Print the receive buffer, if necessary 
     print(receive_buffer) 

    print("Executed all of the commands. Now will exit \n") 
    client.close() 


com = [] 
com.append("sudo ls") 
com.append("cd /home/user/Downloads") 
com.append("sleep 5") 
com.append("ls") 
com.append("pwd") 
com.append("cd /opt/") 
sudo_ssh("myhost.com", "user", "pass", com) 

回答

0

recv_ready方法是檢查是否信道的數據已準備好讀取或不即數據被緩衝或沒有。它不檢查通道本身是否準備好,請參閱 - recv_ready()

因此,您應該將recv_ready() while循環移到receive_buffer = channel.recv(4096)之前,以使其正常工作。