Paramiko recv_ready()返回假值
问题描述:
我想用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)
答
的recv_ready
方法是检查是否信道的数据已准备好读取或不即数据被缓冲或没有。它不检查通道本身是否准备好,请参阅 - recv_ready()。
因此,您应该将recv_ready()
while循环移到receive_buffer = channel.recv(4096)
之前,以使其正常工作。