我正在使用Paramiko尝试抓取主机列表。代码将一直有效,直到列表中的某个主机不可用。它会产生此错误。
File "remote.py", line 12, in <module>
ssh.connect(i, username='user', password='pass')
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 296, in connect
sock.connect(addr)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
我的代码:
#!/usr/bin/python
import paramiko
host = ['cpu1','cpu2','cpu3']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in host:
str(i)
ssh.connect(i, username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('w')
print stdout.readlines()
ssh.close()
我希望脚本能够运行并执行命令。如果它无法连接到主机,则跳过并转到下一个。我错过了带有一些Paramiko参数的if语句吗?
答案 0 :(得分:3)
你可以尝试捕捉异常,处理,如果你愿意,可以继续。
import paramiko
host = ['cpu1','cpu2','cpu3']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in host:
str(i)
try:
ssh.connect(i, username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('w')
print stdout.readlines()
ssh.close()
except Exception as ex:
print "Excetion: %s" % str(ex)
始终正确处理异常不要盲目地使用pass
来逃避它们,这可能导致很难找到错误。
答案 1 :(得分:1)
你错过了任何错误处理;因为documentation explains connect
方法引发了4种不同的例外。在您的情况下,您点击了socket.error
。
如果您想忽略任何连接错误并跳到下一个主机,您可以使用pass
statement忽略这些错误并继续。重要的是不要pass
除了你想要的每个例外。
import paramiko
hosts = ['cpu1','cpu2','cpu3']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in hosts:
try:
ssh.connect(i, username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('w')
print stdout.readlines()
ssh.close()
except socket.error as e:
pass