encoding utf-8 import os import paramiko def get_host_key host hostkey

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# encoding: utf-8
import os
import paramiko
def get_host_key(host):
hostkeytype = None
hostkey = None
# try to load host key from known hosts
try:
host_keys = paramiko.util.load_host_keys(os.path.expanduser("~/.ssh/known_hosts"))
except IOError:
host_keys = {}
if host in host_keys:
hostkeytype = host_keys[host].keys()[0]
hostkey = host_keys[host][hostkeytype]
return hostkeytype, hostkey
def get_private_key(keyfile=None):
key = None
keytype = None
if keyfile is None:
keyfiles = [os.path.expanduser('~/.ssh/id_%s' % keytype) for keytype in ('dsa', 'rsa')]
else:
keyfiles = [keyfile,]
for kf in keyfiles:
try:
key = paramiko.RSAKey.from_private_key_file(kf)
keytype = 'ssh-rsa'
except (IOError, paramiko.SSHException), e:
try:
key = paramiko.DSSKey.from_private_key_file(kf)
keytype = 'ssh-dsa'
except (IOError, paramiko.SSHException), e:
pass
if key is None:
raise paramiko.SSHException('No rsa or dsa keys are available')
return keytype, key
def glob(sftp, path, _transport=None):
use_glob = False
dirname, filename = os.path.split(path)
if filename.startswith('*'):
use_glob = True
match = lambda source, target: source.endswith(target.replace('*', ''))
elif filename.endswith('*'):
use_glob = True
match = lambda source, target: source.startswith(target.replace('*', ''))
if filename.startswith('*') and filename.endswith('*'):
use_glob = True
match = lambda source, target: target.replace('*', '') in source
if use_glob:
filelist = sftp.listdir(dirname)
for i, f in enumerate(filelist):
if match(f, filename):
yield (f, sftp.open(os.path.join(dirname, f)).read())
else:
yield (filename, sftp.open(path).read())
if _transport:
_transport.close()
def get_files(user, host, path, pkeyfile=None):
hostkeytype, hostkey = get_host_key(host)
userkeytype, userkey = get_private_key(pkeyfile)
t = paramiko.Transport((host, 22))
t.connect(hostkey=hostkey, username=user, pkey=userkey)
sftp = paramiko.SFTPClient.from_transport(t)
return glob(sftp, path, t)