如何在python + paramiko中处理套接字错误作为异常?

时间:2011-12-13 14:52:39

标签: python exception error-handling paramiko

我想在引发以下错误时返回错误代码:

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "UserManagementRemote.py", line 202, in create_group
  ssh.connect(hostname, username=user, password=remotepass)
 File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
   sock.connect(addr)
 File "<string>", line 1, in connect
socket.error: [Errno 113] No route to host
>>>

但我目前无法抓住引发的错误。

try:
   ssh = paramiko.SSHClient()
   ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   ssh.connect(hostname, username=user, password=remotepass)
except paramiko.AuthenticationException:
   return 259
except socket.error:
   return 261
chan = ssh.get_transport().open_session()
chan.exec_command(command)
codest = chan.recv_exit_status()
ssh.close()
return codest

结果:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 207, in create_group
  except socket.error:
NameError: global name 'socket' is not defined
>>>

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

待办事项

import socket

在您进行异常处理的模块中。

要防止以后出现此问题,请在所有源文件上运行pyflakes。这也会遇到很多其他错误。