1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 """\
21 Monkey Patch for Python Paramiko
22
23 """
24
25 import paramiko
26
28 """\
29 FIXME!!! --- this method should become part of Paramiko
30
31 This method has been taken from SSHClient class in Paramiko and
32 has been improved and adapted to latest SSH implementations.
33
34 Save the host keys back to a file.
35 Only the host keys loaded with
36 L{load_host_keys} (plus any added directly) will be saved -- not any
37 host keys loaded with L{load_system_host_keys}.
38
39 @param filename: the filename to save to
40 @type filename: str
41
42 @raise IOError: if the file could not be written
43
44 """
45
46
47 if self.known_hosts is not None:
48 self.load_host_keys(self.known_hosts)
49
50 f = open(filename, 'w')
51
52 _host_keys = self.get_host_keys()
53 for hostname, keys in _host_keys.iteritems():
54
55 for keytype, key in keys.iteritems():
56 f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
57
58 f.close()
59
60
62 """\
63 Read a file of known SSH host keys, in the format used by openssh.
64 This type of file unfortunately doesn't exist on Windows, but on
65 posix, it will usually be stored in
66 C{os.path.expanduser("~/.ssh/known_hosts")}.
67
68 If this method is called multiple times, the host keys are merged,
69 not cleared. So multiple calls to C{load} will just call L{add},
70 replacing any existing entries and adding new ones.
71
72 @param filename: name of the file to read host keys from
73 @type filename: str
74
75 @raise IOError: if there was an error reading the file
76
77 """
78 f = open(filename, 'r')
79 for line in f:
80 line = line.strip()
81 if (len(line) == 0) or (line[0] == '#'):
82 continue
83 e = paramiko.hostkeys.HostKeyEntry.from_line(line)
84 if e is not None:
85 _hostnames = e.hostnames
86 for h in _hostnames:
87 if self.check(h, e.key):
88 e.hostnames.remove(h)
89 if len(e.hostnames):
90 self._entries.append(e)
91 f.close()
92
93
94 -def _HostKeys_add(self, hostname, keytype, key, hash_hostname=True):
95 """\
96 Add a host key entry to the table. Any existing entry for a
97 C{(hostname, keytype)} pair will be replaced.
98
99 @param hostname: the hostname (or IP) to add
100 @type hostname: str
101 @param keytype: key type (C{"ssh-rsa"} or C{"ssh-dss"})
102 @type keytype: str
103 @param key: the key to add
104 @type key: L{PKey}
105
106 """
107 for e in self._entries:
108 if (hostname in e.hostnames) and (e.key.get_name() == keytype):
109 e.key = key
110 return
111 if not hostname.startswith('|1|') and hash_hostname:
112 hostname = self.hash_host(hostname)
113 self._entries.append(paramiko.hostkeys.HostKeyEntry([hostname], key))
114
115
117 paramiko.SSHClient.save_host_keys = _SSHClient_save_host_keys
118 paramiko.hostkeys.HostKeys.load = _HostKeys_load
119 paramiko.hostkeys.HostKeys.add = _HostKeys_add
120