简体   繁体   English

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

[英]how to handle socket errors as exceptions in python + paramiko?

I want to return an error code when the following error gets raised: 出现以下错误时,我想返回一个错误代码:

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
>>>

But I'm currently having trouble catching the error raised. 但是我目前无法捕获所引发的错误。

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

Resulting on this: 结果:

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
>>>

Any ideas? 有任何想法吗?

Do

import socket

in the module where you do the exception handling. 在执行异常处理的模块中。

To prevent this problem in the future, run pyflakes on all your source files. 为防止将来出现此问题, 在所有源文件上运行pyflakes That will catch a lot of other errors as well. 那也会捕获很多其他错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM