-
Notifications
You must be signed in to change notification settings - Fork 3
/
ssh.py
162 lines (129 loc) · 4.75 KB
/
ssh.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#
# Copyright 2017 Sangoma Technologies Inc.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
'''
Paramiko machine ctl
'''
import os
import types
import logging
import plumbum
from stat import S_ISDIR
from plumbum import ProcessExecutionError
from paramiko import SSHException
from paramiko.agent import Agent as SSHAgent
from paramiko.ssh_exception import AuthenticationException
log = logging.getLogger(__name__)
# Rexport plumbum errors
SSHCommsError = plumbum.machines.session.SSHCommsError
ProcessExecutionError = plumbum.ProcessExecutionError
SSH_OPTS = ['-o', 'UserKnownHostsFile=/dev/null',
'-o', 'StrictHostKeyChecking=no',
'-o', 'ServerAliveInterval=5']
def walk(self, remotepath):
"""Taken from https://gist.github.com/johnfink8/2190472
A stripped down version of os.walk implemented for sftp which
yields tuples: (path, folders, files)
"""
path = remotepath
files = []
folders = []
for f in self.listdir_attr(remotepath):
if S_ISDIR(f.st_mode):
folders.append(f.filename)
else: # non-dir
files.append(f.filename)
yield path, folders, files
for folder in folders:
new_path = os.path.join(remotepath, folder)
for x in self.walk(new_path):
yield x
def get_paramiko_sftp(hostname, **kwargs):
ssh = get_paramiko_ssh(hostname, **kwargs)
return ssh.sftp
def get_paramiko_ssh(hostname, **kwargs):
from paramiko import AutoAddPolicy
from plumbum.machines.paramiko_machine import ParamikoMachine
password = kwargs.get('password')
keyfile = kwargs.get('keyfile')
settings = {'user': kwargs.get('user', 'root'),
'port': kwargs.get('port', 22),
'look_for_keys': False,
'missing_host_policy': AutoAddPolicy(),
'keep_alive': 60}
if password:
settings['password'] = password
if keyfile:
settings['keyfile'] = keyfile
ssh = ParamikoMachine(hostname, **settings)
ssh.sftp.walk = types.MethodType(walk, ssh.sftp)
return ssh
def get_generic_sftp(hostname, **kwargs):
import paramiko
port = kwargs.get('port', 22)
username = kwargs.get('user', 'root')
password = kwargs.get('password')
keyfile = kwargs.get('keyfile')
def get_transport(**kwargs):
transport = paramiko.Transport(hostname, port)
transport.connect(**kwargs)
return transport
def get_sftp(transport):
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.walk = types.MethodType(walk, sftp)
return sftp
def iter_credentials():
if keyfile:
log.info("Offering keyfile {}...".format(keyfile))
pkey = paramiko.RSAKey.from_private_key_file(keyfile)
yield {'username': username, 'pkey': pkey}
if password:
log.info("Offering password...")
yield {'username': username, 'password': password}
if 'SSH_AUTH_SOCK' in os.environ:
agent = SSHAgent()
for pkey in agent.get_keys():
log.info("Offering {} key from agent...".format(pkey.name))
yield {'username': username, 'pkey': pkey}
err = None
transport = None
log.info("Trying SSH connection to {}...".format(hostname))
for credentials in iter_credentials():
err = None
try:
transport = get_transport(**credentials)
break
except AuthenticationException as _:
err = _
log.warning("Authentication failed: {}".format(err))
if err or not transport:
raise EnvironmentError('Failed to establish ssh transport')
return get_sftp(transport)
def get_generic_ssh(hostname, **kwargs):
from plumbum import SshMachine
password = kwargs.get('password')
keyfile = kwargs.get('keyfile')
settings = {'user': kwargs.get('user', 'root'),
'port': kwargs.get('port', 22),
'ssh_opts': SSH_OPTS,
'scp_opts': SSH_OPTS}
if password:
settings['password'] = kwargs.get('password')
if keyfile:
keyfile = os.path.expanduser(keyfile)
assert os.path.isfile(keyfile), 'No keyfile {} exists?'.format(keyfile)
log.debug("Attempting to auth ssh with keyfile {}".format(keyfile))
settings['keyfile'] = keyfile
elif password:
settings['password'] = kwargs.get('password')
ssh = SshMachine(hostname, **settings)
return ssh
if os.environ.get('PLUMBUM_BACKEND') == 'paramiko':
get_ssh = get_paramiko_ssh
get_sftp = get_paramiko_sftp
else:
get_ssh = get_generic_ssh
get_sftp = get_generic_sftp