0

I m the way to upload files over sftp using paramiko but i am getting this error.

ri@ri-desktop:~/workspace/ssh$ python testssh.py
Traceback (most recent call last):
File "testssh.py", line 75, in
if host_keys.has_key(hostname):
AttributeError: 'HostKeys' object has no attribute 'has_key'

This is the code inside my 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)
Raja Simon
  • 10,126
  • 5
  • 43
  • 74

3 Answers3

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

Either one of these functions runs successfully and returns an object that doesn't have a has_key attribute, or you're using python 3, where has_key has been removed from dicts.

Since you are using python 2.x, the problem should be that these functions return something that is doesn't have has_key attribute

I had a look at the source code for paramiko.util and indeed, util.load_host_keys returns something else than a dict, namely a HostKeys object which does not implement has_key(), so you cannot call that function on your host_keys object

Because the docstring for HostKeys class says this

A .HostKeys object can be treated like a dict; any dict lookup is equivalent to calling lookup.

you could use this instead

if hostname in host_keys:
Community
  • 1
  • 1
Tim
  • 41,901
  • 18
  • 127
  • 145
0

just test if host_keys is a dictionary by adding this piece of code:print type(host_keys)

before if host_keys.has_key(hostname):

hemraj
  • 964
  • 6
  • 14
0

What version of Python do you use ? Because has_key has been deprecated in 3.xx :

Removed. dict.has_key() – use the in operator instead.

Source : https://docs.python.org/3.1/whatsnew/3.0.html

lucasg
  • 10,734
  • 4
  • 35
  • 57