gpt4 book ai didi

python - Paramiko 问题 - 执行命令时 channel 关闭

转载 作者:行者123 更新时间:2023-11-30 23:06:23 24 4
gpt4 key购买 nike

我一直在尝试在 Overture Box 上运行命令使用paramiko建立SSH连接。

我的脚本确实正确连接到盒子,没有看到任何问题,当脚本运行 exec_command(cmd) 方法时出现问题:

Traceback (most recent call last):
File "test.py", line 39, in <module>
stdin, stdout, stderr = ssh.exec_command("version")
File "/opt/csw/lib/python2.7/site-packages/paramiko/client.py", line 345, in exec_command
chan.exec_command(command)
File "/opt/csw/lib/python2.7/site-packages/paramiko/channel.py", line 60, in _check
return func(self, *args, **kwds)
File "/opt/csw/lib/python2.7/site-packages/paramiko/channel.py", line 229, in exec_command
self._wait_for_event()
File "/opt/csw/lib/python2.7/site-packages/paramiko/channel.py", line 1086, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed.

使用 Linux Box 作为目标主机的相同脚本会产生正确的结果

代码是借来的,我刚刚在谷歌上找到了片段:

import sys
import time
import select
import paramiko

host = raw_input("Hostname?: ")
i = 1
password = raw_input("Password?: ")


#
# Try to connect to the host.
# Retry a few times if it fails.
#
while True:
print "Trying to connect to %s (%i/30)" % (host, i)

try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port=22, username="username", password=password)
print "Connected to %s" % host
break
except paramiko.AuthenticationException:
print "Authentication failed when connecting to %s" % host
sys.exit(1)
except:
print "Could not SSH to %s, waiting for it to start" % host
i += 1
time.sleep(2)

# If we could not connect within time limit
if i == 30:
print "Could not connect to %s. Giving up" % host
sys.exit(1)

# Send the command (non-blocking)
stdin, stdout, stderr = ssh.exec_command("version")

# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
if len(rl) > 0:
# Print data from stdout
print stdout.channel.recv(1024),

#
# Disconnect from the host
#
print "Command done, closing SSH connection"
ssh.close()

我发现了其他问题,据说该问题可能与主机中的 SFTP 设置有关,但我可以这样做:

sftp username@hostname

我在 Google 上搜索了一段时间,但到目前为止找不到任何有用的信息。

预先感谢您的帮助。

编辑:差点忘了,我知道问题出在:

stdin, stdout, stderr = ssh.exec_command("version")

我已经以交互方式运行了整个脚本,当我运行该行时它就中断了。

最佳答案

可能是 Overture 不支持 SSH exec_command 请求。

我需要使用 transport.open_session()session.get_pty()session.invoke_shell() 来设置交互式 shell session ,然后使用 session.send()session.recv() 写入/读取 Cisco 交换机和其他网络设备的 shell session ,当 exec_command() 不可用。

关于python - Paramiko 问题 - 执行命令时 channel 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697981/

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