-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsshcontroller.py
More file actions
265 lines (219 loc) · 6.92 KB
/
sshcontroller.py
File metadata and controls
265 lines (219 loc) · 6.92 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import errno
import logging
import paramiko
import socket
from os import path
from stat import S_ISDIR, S_ISREG
_KEY_TYPES = {
"dsa": paramiko.DSSKey,
"rsa": paramiko.RSAKey,
"ecdsa": paramiko.ECDSAKey,
"ed25519": paramiko.Ed25519Key,
}
class SFTPController(paramiko.SFTPClient):
def __init__(self, sock):
super().__init__(sock)
def exists(self, path):
try:
self.stat(path)
except IOError as e:
return e.errno != errno.ENOENT
return True
def list_dirs(self, path):
return [
d.filename for d in self.listdir_attr(path) if S_ISDIR(d.st_mode)
]
def list_files(self, path):
return [
f.filename for f in self.listdir_attr(path) if S_ISREG(f.st_mode)
]
@classmethod
def from_transport(cls, t):
chan = t.open_session()
chan.invoke_subsystem("sftp")
return cls(chan)
class SSHController:
def __init__(
self,
host,
user,
key_path=None,
key_password=None,
key_type="rsa",
ssh_password=None,
port=22,
):
self.host = host
self.user = user
self.ssh_password = ssh_password if key_path is None else None
self.port = port
self.nb_bytes = 1024
self.keys, self.transport = [], None
key_type = key_type.lower()
if key_path:
self.keys.append(
_KEY_TYPES[key_type].from_private_key(
open(path.expanduser(key_path), 'r'),
key_password,
)
)
elif ssh_password is None:
self.keys = paramiko.Agent().get_keys()
try:
key_file = _KEY_TYPES[key_type].from_private_key(
open(path.expanduser(f"~/.ssh/id_{key_type}"), 'r'),
key_password
)
except Exception:
pass
else:
self.keys.insert(
len(self.keys) if key_password is None else 0, key_file
)
if not self.keys:
logging.error("No valid key found")
def connect(self):
try:
ssh_socket = socket.create_connection((self.host, self.port))
except OSError as e:
logging.error(f"Connection failed: {e.strerror}")
return 1
self.transport = paramiko.Transport(ssh_socket)
if self.ssh_password is not None:
try:
self.transport.connect(
username=self.user,
password=self.ssh_password,
)
except paramiko.SSHException:
pass
else:
for key in self.keys:
try:
self.transport.connect(username=self.user, pkey=key)
except paramiko.SSHException:
continue
break
if not self.transport.is_authenticated():
logging.error("SSH negotiation failed")
return 1
logging.info(f"Successfully connected to {self.user}@{self.host}")
return 0
def __run_until_event(
self,
command,
stop_event,
display=True,
capture_output=False,
shell=True,
combine_stderr=False,
):
channel = self.transport.open_session()
output = ""
channel.settimeout(2)
channel.set_combine_stderr(combine_stderr)
if shell:
channel.get_pty()
channel.exec_command(command)
if not display and not capture_output:
stop_event.wait()
else:
while True:
try:
raw_data = channel.recv(self.nb_bytes)
except socket.timeout:
if stop_event.is_set():
break
continue
if not len(raw_data):
break
data = raw_data.decode("utf-8")
if display:
print(data, end='')
if capture_output:
output += data
if stop_event.is_set():
break
channel.close()
if not channel.exit_status_ready():
return (0, output.splitlines())
return (channel.recv_exit_status(), output.splitlines())
def __run_until_exit(
self,
command,
timeout,
display=True,
capture_output=False,
shell=True,
combine_stderr=False,
):
channel = self.transport.open_session()
output = ""
channel.settimeout(timeout)
channel.set_combine_stderr(combine_stderr)
if shell:
channel.get_pty()
channel.exec_command(command)
try:
if not display and not capture_output:
return (channel.recv_exit_status(), output.splitlines())
else:
while True:
raw_data = channel.recv(self.nb_bytes)
if not len(raw_data):
break
data = raw_data.decode("utf-8")
if display:
print(data, end='')
if capture_output:
output += data
except socket.timeout:
logging.warning(f"Timeout after {timeout}s")
return (1, output.splitlines())
except KeyboardInterrupt:
logging.info("KeyboardInterrupt")
return (0, output.splitlines())
finally:
channel.close()
return (channel.recv_exit_status(), output.splitlines())
def run(
self,
command,
display=False,
capture_output=False,
shell=True,
combine_stderr=False,
timeout=None,
stop_event=None,
):
if stop_event:
return self.__run_until_event(
command,
stop_event,
display=display,
shell=shell,
combine_stderr=combine_stderr,
capture_output=capture_output,
)
else:
return self.__run_until_exit(
command,
timeout,
display=display,
shell=shell,
combine_stderr=combine_stderr,
capture_output=capture_output,
)
def disconnect(self):
if self.transport:
self.transport.close()
def __getattr__(self, target):
def wrapper(*args, **kwargs):
if not self.transport.is_authenticated():
logging.error("SSH session is not ready")
return 1
sftp_channel = SFTPController.from_transport(self.transport)
r = getattr(sftp_channel, target)(*args, **kwargs)
sftp_channel.close()
return r
return wrapper