本文介绍了““连接"对象没有属性"_sftp_live""pysftp连接失败时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到主机***的主机密钥" 时,我想很好地捕获错误,并向最终用户提供适当的消息.我试过了:

I'd like to catch nicely the error when "No hostkey for host *** is found" and give an appropriate message to the end user. I tried this:

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)

但是不幸的是输出不是很好:

but unfortunately the output is not very nice:

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:除外:?

How to nicely avoid these last lines / this "exception ignored" with a try: except:?

推荐答案

@reverse_engineer进行的分析是正确的.但是:

The analysis by @reverse_engineer is correct. However:

  1. 似乎还定义了另外一个属性 self._transport .
  2. 可以暂时纠正问题 ,直到通过将 pysftp.Connection 类子类化为永久性修复程序为止,如下所示:
  1. It seems that an additional attribute, self._transport, also is defined too late.
  2. The problem can be temporarily corrected until a permanent fix comes by subclassing the pysftp.Connection class as follows:
import pysftp
import paramiko


class My_Connection(pysftp.Connection):
    def __init__(self, *args, **kwargs):
        self._sftp_live = False
        self._transport = None
        super().__init__(*args, **kwargs)

try:
    with My_Connection('1.2.3.4', username='root', password='') as sftp:
        l = sftp.listdir()
        print(l)
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)

这篇关于““连接"对象没有属性"_sftp_live""pysftp连接失败时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:34