gpt4 book ai didi

使用多个命令的 Python paramiko 模块

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:21 24 4
gpt4 key购买 nike

我有一个创建连接的类。我可以在 channel 关闭之前连接并执行 1 个命令。在我拥有的另一个系统上,我可以执行多个命令并且 channel 不会关闭。显然这是我尝试连接的系统的配置问题。

class connect:

newconnection = ''

def __init__(self,username,password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect('somehost', username=username,password=password,port=2222,timeout=5)
except:
print "Count not connect"
sys.exit()
self.newconnection = ssh

def con(self):
return self.newconnection

然后我使用'ls'命令来打印一些输出

sshconnection = connect('someuser','somepassword').con()


stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")

print stdout.readlines()
print stdout

stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")

print stdout.readlines()
print stdout

sshconnection.close()
sys.exit()

在第一个 exec_command 运行后,它打印目录列表的预期输出。当我在第一个 exec_command 之后打印 stdout 时,看起来 channel 已关闭

<paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0x2400f10L (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>>> 

就像我在另一个系统上所说的那样,我能够继续运行命令并且连接不会关闭。有没有办法让我保持打开状态?还是我可以看到它关闭的原因的更好方法?

编辑:所以看起来每个 SSHClient.exec_command 只能运行 1 个命令...所以我决定 get_transport().open_session() 然后运行一个命令。第一个总是有效。第二个总是失败,脚本挂起

最佳答案

exec_command 执行后仅使用 paramiko 关闭 channel ,ssh 返回一个授权提示。

似乎仅使用 paramiko 是不可能的,请尝试使用 fabric 或其他工具。

** fabric did not work out too .

关于使用多个命令的 Python paramiko 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709872/

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