我的代码存在问题。输出很小时工作正常,但输出很大时会断开。
这是我的代码:
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.
根据plink ssh not working with multiple commands passed in a file. - 65059 - The Cisco Learning Network的说法,这是Cisco路由器的一个问题,因此与Python无关。
sleep
,但这对于脚本编写是不可靠的。事实上,最后一个似乎是正确的解释。触发连接丢弃的不是EOF,而是恰好包含它的命令之后的附加数据。第一个链接的另一个解决方法是在输入命令之间插入几个换行符 - 以这种方式查看事物,它们用作填充代替破坏的传输逻辑否则会插入自身并阻塞它的一个填充。