【发布时间】:2021-03-08 04:26:31
【问题描述】:
我想很好地捕捉到 “找不到主机 *** 的主机密钥”时的错误,并向最终用户提供适当的消息。我试过这个:
import pysftp, paramiko
try:
with pysftp.Connection('1.2.3.4', username='root', password='') as sftp:
sftp.listdir()
except paramiko.ssh_exception.SSHException as e:
print('SSH error, you need to add the public key of your remote in your local known_hosts file first.', e)
但不幸的是输出不是很好:
SSH error, you need to add the public key of your remote in your local known_hosts file first. No hostkey for host 1.2.3.4 found.
Exception ignored in: <function Connection.__del__ at 0x00000000036B6D38>
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\pysftp\__init__.py", line 1013, in __del__
self.close()
File "C:\Python37\lib\site-packages\pysftp\__init__.py", line 784, in close
if self._sftp_live:
AttributeError: 'Connection' object has no attribute '_sftp_live'
如何使用try: except: 很好地避免这些最后几行/这个“忽略异常”?
【问题讨论】:
-
截至 2022 年,pysftp 似乎是一个废弃的项目。我建议你切换到 Paramiko。 pysftp 只是 Paramiko 的一个包装器。所以如果你有 pysftp,你也有 Paramiko。见pysftp vs. Paramiko。
标签: python exception sftp paramiko pysftp