gpt4 book ai didi

python - "' 连接 ' object has no attribute ' _sftp_live '"当 pysftp 连接失败

转载 作者:行者123 更新时间:2023-12-04 14:39:34 24 4
gpt4 key购买 nike

当“找不到主机 *** 的主机 key ”时,我想很好地捕获错误并向最终用户提供适当的消息。我试过这个:

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: 很好地避免这些最后几行/这个“忽略异常” ?

最佳答案

@reverse_engineer 的分析是正确的。然而:

  • 好像多了一个属性,self._transport ,也定义为时已晚。
  • 通过子类化 pysftp.Connection 可以暂时更正该问题,直到永久修复出现。类如下:
  • 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)
    更新
    我无法在桌面上复制此错误。但是,我在 pysftp 的来源中看到在它初始化其 _cnopts 的代码中属性与 self._cnopts = cnopts or CnOpts()哪里 cnoptspysftp.Connection 的关键字参数构造函数,并且有可能是 CnOpts构造函数抛出 HostKeysException如果未找到主机 key 导致 _cnopts 的异常未设置属性。
    尝试以下更新的代码,让我知道它是否有效:
    import pysftp
    import paramiko

    class My_Connection(pysftp.Connection):
    def __init__(self, *args, **kwargs):
    try:
    if kwargs.get('cnopts') is None:
    kwargs['cnopts'] = pysftp.CnOpts()
    except pysftp.HostKeysException as e:
    self._init_error = True
    raise paramiko.ssh_exception.SSHException(str(e))
    else:
    self._init_error = False

    self._sftp_live = False
    self._transport = None
    super().__init__(*args, **kwargs)

    def __del__(self):
    if not self._init_error:
    self.close()

    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)

    关于python - "' 连接 ' object has no attribute ' _sftp_live '"当 pysftp 连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65002585/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com