HostKeys'对象没有属性'has_key

0 投票
3 回答
3658 浏览
提问于 2025-04-18 10:46

我正在尝试使用paramiko通过sftp上传文件,但遇到了一个错误。

ri@ri-desktop:~/workspace/ssh$ python testssh.py
错误追踪(最近的调用在最前面):
文件 "testssh.py",第75行,
如果 host_keys.has_key(hostname):
AttributeError: 'HostKeys' 对象没有 'has_key' 这个属性

这是我在test.py中的代码

hostkeytype = None
hostkey = None
files_copied = 0

try:
    host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))<br/>

except IOError: 
    try:
        # try ~/ssh/ too, e.g. on windows
        host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
    except IOError:
        print '*** Unable to open host keys file'
        host_keys = {}
if host_keys.has_key(hostname):
    hostkeytype = host_keys[hostname].keys()[0]

    hostkey = host_keys[hostname][hostkeytype]
    print 'Using host key of type {0}'.format(hostkeytype)

3 个回答

0

你用的是什么版本的Python呢?因为在3.xx版本中,has_key这个功能已经被淘汰了:

已经移除。dict.has_key() – 现在请使用in操作符。

来源:https://docs.python.org/3.1/whatsnew/3.0.html

0

只需要加一段代码来测试一下 host_keys 是否是一个字典,代码是:print type(host_keys)

放在 if host_keys.has_key(hostname): 之前就可以了。

2
paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))

这两个函数要么成功运行并返回一个没有 has_key 属性的对象,要么你在使用 Python 3,因为在 Python 3 中,has_key 已经从字典中移除了

既然你在使用 Python 2.x,问题应该是这些函数返回的东西没有 has_key 属性。

我查看了一下 paramiko.util 的源代码,确实发现 util.load_host_keys 返回的不是字典,而是一个 HostKeys 对象,这个对象没有实现 has_key(),所以你不能在你的 host_keys 对象上调用这个函数。

因为 HostKeys 类的文档说明是这样的:

一个 .HostKeys 对象可以像字典一样使用;任何字典查找都等同于调用 lookup

所以你可以用这个来代替。

if hostname in host_keys:

撰写回答