python - Paramiko recv_ready() 返回假值

标签 python paramiko

我尝试使用 paramiko 远程执行多个命令,但是 recv_ready() 未返回正确的值。
例如,在执行pwd\n命令之后,它将连续报告 channel 尚未准备好(显然是错误的)。对于某些命令它可以正常工作,例如ls。 我正在做的事情有问题吗,或者 paramiko 有问题吗?

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方法是检查 channel 的数据是否准备好读取,即数据是否被缓冲。它不会检查 channel 本身是否已准备好,请参阅 - recv_ready() .

所以你应该移动 recv_ready() while 循环就在 receive_buffer = channel.recv(4096) 之前使其发挥作用。

关于python - Paramiko recv_ready() 返回假值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40451767/

相关文章:

python - 如果列表索引存在,做 X

Python-将全局变量分配给函数返回需要函数是全局的吗?

带有语句 : 'Syntax error: invalid syntax' 的 Python

python - paramiko 中的身份验证异常

python - Python 中的 "name S_ISREG is not defined"

通过 socks(代理)的 Python ssh 客户端

python - 如何将 Paramiko stdin、stdout 和 stderr 连接到控制台?

python - 从文本文件中删除字符串保持 float

python - 在保持标签的同时将大范围压缩为 python 中的较短范围

python - 使用 Python Paramiko 通过 SSH 将输入/变量传递给命令/脚本