当对Cisco路由器的ssh命令产生大量输出时,subprocess.CalledProcessError和ssh连接丢失

问题描述 投票:1回答:1

我的代码存在问题。输出很小时工作正常,但输出很大时会断开。

这是我的代码:

def listDevices(username, pass, regex):
    command = "list-dev " + regex
    deviceArray = []
    connectString = "plink -ssh -l " + username + " -pw " + pass + " -P " + SshPort + " " + Server + " \"" + command + "\""
    rawList = subprocess.check_output(connectString, shell=True)
          for line in rawList.split("\r\n"):
              if "" is not line:
                  deviceArray.append(line)
          print deviceArray
          return deviceArray

Server = 10.10.10.1
SshPort = 22 
username = "test"
pass - "password"  
regex = "rt*mdr*"    

mdrList = listDevices(username, pass, regex)
print mdrList

这在数据较小时工作正常,但在数据较大时失败。

这是错误:

subprocess.CalledProcessError: Command 'plink -ssh -l test -pw password -P 4000 10.10.10.1 "list-dev *"' returned non-zero exit status 1

编辑:

我取代了plink并写了paramiko,但仍未获得所有数据。这是代码:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username=username, password=password, port = 9000)
list =["list-devices rt*"]
command = '\n'.join(list)
print command
stdin,stdout,stderr = ssh.exec_command(command)
print stdout.read()

它给我以下错误:

Traceback (most recent call last):
  File "C:/Users/xx/Scripts/Test2.py", line 31, in <module>
    stdin,stdout,stderr = ssh.exec_command(command)
  File "C:\Python27\paramiko\client.py", line 404, in exec_command
    chan.exec_command(command)
  File "C:\Python27\paramiko\channel.py", line 60, in _check
    return func(self, *args, **kwds)
  File "C:\Python27\paramiko\channel.py", line 229, in exec_command
    self._wait_for_event()
  File "C:\Python27\paramiko\channel.py", line 1086, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
python python-2.7 subprocess cisco
1个回答
1
投票

根据plink ssh not working with multiple commands passed in a file. - 65059 - The Cisco Learning Network的说法,这是Cisco路由器的一个问题,因此与Python无关。

  • SSH using public key authentication to ... - Cisco Support Community说,一旦思科在输入上看到EOF,它就会丢弃连接的两端,即使根据TCP规则,它应该只关闭输入套接字。它建议的解决方法是延迟EOF直到所有输出都被下载。它使用快速和脏的sleep,但这对于脚本编写是不可靠的。
  • Putty Dies with Large Output : networking - Reddit说这是一个MTU问题。症状无法获得超过一个屏幕的信息: 我遇到了一些MTU相关的问题,这些问题以类似的方式表现在终端仿真器中。通常它是在VLAN中携带的某种点对点租用线路,其中添加的用于标记的字节会混乱并丢弃传输中的帧。当发生这种情况时,较短的输出将会很好,但更长的输出将会导致会话中断。有时优雅,有时则不优雅。

事实上,最后一个似乎是正确的解释。触发连接丢弃的不是EOF,而是恰好包含它的命令之后的附加数据。第一个链接的另一个解决方法是在输入命令之间插入几个换行符 - 以这种方式查看事物,它们用作填充代替破坏的传输逻辑否则会插入自身并阻塞它的一个填充。

© www.soinside.com 2019 - 2024. All rights reserved.