gpt4 book ai didi

python - Paramiko recv_ready() 返回假值

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:43 28 4
gpt4 key购买 nike

我尝试使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com