您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

仅使用服务器指纹即可使用pysftp和Python 3连接到SFTP服务器

仅使用服务器指纹即可使用pysftp和Python 3连接到SFTP服务器

可以在Python中找到解决方案-pysftp / paramiko- 使用其指纹验证主机密钥,但是我必须对其进行一些改动才能使用Python 3。

import hashlib as hl


def trim_fingerprint(fingerprint):
    #if fingerprint.startswith('ecdsa-sha2-nistp384 384 '):
        #return fingerprint[len('ecdsa-sha2-nistp384 384 '):]
    return fingerprint


def clean_fingerprint(fingerprint):
    #return trim_fingerprint(fingerprint).replace(':', '')
    return trim_fingerprint(fingerprint)

class FingerprintKey:

    def __init__(self, fingerprint):
        self.fingerprint = clean_fingerprint(fingerprint)

    def compare(self, other):
        if callable(getattr(other, "get_fingerprint", None)):
            return other.get_fingerprint() == self.fingerprint
        elif clean_fingerprint(other) == self.get_fingerprint():
            return True
        #elif hl.md5(other).digest().encode('hex') == self.fingerprint:
        #The line below is required for Python 3.  Above is Python 2.
        elif hl.md5(other).hexdigest() == self.fingerprint:
            return True
        else:
            return False

    def __cmp__(self, other):
        return self.compare(other)

    def __contains__(self, other):
        return self.compare(other)

    def __eq__(self, other):
        return self.compare(other)

    def __ne__(self, other):
        return not self.compare(other)

    def get_fingerprint(self):
        return self.fingerprint

    def get_name(self):
        return u'ecdsa-sha2-nistp384'

    def asbytes(self):
         # Note: This returns itself.
         #   That way when comparisons are done to asbytes return value,
         #   this class can handle the comparison.
        return self

我必须手动从指纹中删除任何“:”,因为它从未允许脚本执行此操作。

用法

options = pysftp.CnOpts()
options.hostkeys.clear()
options.hostkeys.add('www.sample.com', u'ecdsa-sha2-nistp384 384 ', AuthOnFingerPrint.FingerprintKey(serverkey))

其中serverkey是指纹。

python 2022/1/1 18:33:18 有547人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶