-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcmd_executor.py
More file actions
322 lines (239 loc) · 9.16 KB
/
Copy pathcmd_executor.py
File metadata and controls
322 lines (239 loc) · 9.16 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import os
import errno
import fcntl
import select
import signal
import logging
import subprocess
import paramiko
plogger = paramiko.util.get_logger('paramiko.transport')
plogger.setLevel(logging.ERROR)
class CMDExecutor(object):
"""Base implementation for local and SSH command executions"""
def __init__(self):
"""Preconfigure class"""
self.last_result = None
self.last_stdout = None
self.stdin = None
def getLastResult(self):
"""get last results"""
if self.last_result is None:
raise RuntimeError("no last result available")
return self.last_result
def execute(self, *cmd):
"""Execute command pure virtual func"""
raise RuntimeError("Pure virtual fucntion call")
def exec_simple_check(self,*cmd):
"""Execute command and check ret code"""
res = self.exec_simple(*cmd)
assert 0 == res, "Cmd %r exited with code %s. Output: %r" \
% (cmd, self.last_result, self.last_stdout)
def exec_simple(self,*cmd):
"""execute command without checking return code"""
stdout = []
for i in self.execute(*cmd):
stdout.append(i)
self.last_stdout = "".join(stdout)
return self.last_result
def send(self, data):
"""Send data to command stdin"""
self.stdin.write(data)
self.stdin.flush()
class SSHCMDExecutor(CMDExecutor):
"""Class implements command execution over SSH"""
def __init__(self, host, username, password, port=22, timeout = None):
"""Store SSH parameters"""
super(SSHCMDExecutor,self).__init__()
self.ssh = paramiko.SSHClient()
self.ssh.load_system_host_keys()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(host, 22, username=username,
password=password)
#allow_agent=False,
#timeout = timeout)
self.host = host
self.user = username
self.password = password
def __del__(self):
self.close()
def close(self):
if self.ssh is not None:
self.ssh.close()
self.ssh = None
def __enter__(self):
return self
def __exit__(self, x, y, z):
self.close()
def execute(self, *cmd):
"""Execute command over SSH"""
self.chan = self.ssh.get_transport().open_session()
try:
self.chan.setblocking(False)
self.chan.exec_command(" ".join(cmd))
outs = {'out':"",'err':""}
continue_loop = True
while continue_loop:
if self.chan.exit_status_ready():
continue_loop = False
try:
select.select([self.chan], [], [], 0.1)
except:
continue
while self.chan.recv_ready():
outs['out'] += self.chan.recv(10280)
while self.chan.recv_stderr_ready():
outs['err'] += self.chan.recv_stderr(10280)
for key,data in outs.items():
lns = data.split('\n')
for dt in lns[:-1]:
yield dt + "\n"
outs[key] = lns[-1]
for i in outs.values():
if i != "":
yield i
self.last_result = self.chan.recv_exit_status()
finally:
self.chan.close()
self.chan = None
@classmethod
def connect(cls, url, *dt, **mp):
user_passwd, host_port = url.split('@')
user, passwd = user_passwd.split(':',1)
if ':' in host_port:
host,port = host_port.split(':')
else:
port = 22
host = host_port
return cls(host, user, passwd, port, *dt, **mp)
def get_fl(self, path):
t = paramiko.Transport((self.host, 22))
t.connect(username=self.user,
password=self.password, hostkey=None)
sftp = paramiko.SFTPClient.from_transport(t)
res = sftp.open(path, "rb").read()
t.close()
return res
class LocalCMDCanceled(Exception):
"""Raised when CMD canceled"""
pass
class LocalCMDExecutor(CMDExecutor):
"""Class implements local command execution"""
# If set to True all current unsafe commands are interrupted,
# all future unsafe commands raise LocalCMDCanceled exception
cancel = False
def __init__(self, set_new_group=False, safe=False, env=None, cwd=None):
"""Create a LocalCMDExecutor object
@param set_new_group: whether execute child process in new group
(default - False)
@type set_new_group: bool
@param safe: safe commands can be executed after cancel_all,
these commands will not hang and can be used for cleanup
@type safe: bool
@param env: environment for child process
@type env: dict
"""
super(LocalCMDExecutor, self).__init__()
self.safe = safe
self.signal_sent = False
if self.cancel and not self.safe:
raise LocalCMDCanceled()
self.set_new_group = set_new_group
self.nowait = False
self.env = env
self.cwd = cwd
@classmethod
def cancel_all(cls):
"""Cancel current and all future local unsafe cmds"""
cls.cancel = True
def set_nowait(self, nowait):
"""If nowait is set to True execute() will yield
empty string if no data is in stdout"""
self.nowait = nowait
def _set_nonblock(self, stream):
"""Set O_NONBLOCK flag for given stream"""
fdesc = stream.fileno()
flags = fcntl.fcntl(fdesc, fcntl.F_GETFL)
fcntl.fcntl(fdesc, fcntl.F_SETFL, flags | os.O_NONBLOCK)
def execute(self, *cmd):
"""Execute command locally"""
self.last_result = None
if self.set_new_group:
preexec_fn = os.setsid
else:
preexec_fn = None
self.proc = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
preexec_fn=preexec_fn,
env=self.env,
cwd=self.cwd)
proc = self.proc
self.pid = self.proc.pid
self.pgid = os.getpgid(self.proc.pid)
logger.debug("New cmd with pid {0} : {1}".format(self.pid,
" ".join(cmd)))
self._set_nonblock(proc.stdout)
self.stdin = proc.stdin
for i in self.deferred:
self.stdin.write(i)
self.deferred = []
try:
while True:
try:
if self.cancel and not self.signal_sent and not self.safe:
# do not send signal second time
self.signal_sent = True
if self.set_new_group:
self.send_signal_to_group(signal.SIGTERM)
else:
self.send_signal(signal.SIGTERM)
dt = proc.stdout.read()
if dt == '':
break
#logger.debug("Output from pid: {0} {1}".format(self.pid,dt))
yield dt
except IOError:
# EWOULDBLOCK
if self.nowait:
yield ''
try:
select.select([proc.stdout], [], [], 1)
except select.error:
# select.error: (4, 'Interrupted system call') - ignore it,
# just call select again
pass
self.wait_proc_finished(proc)
if self.signal_sent:
raise LocalCMDCanceled(list(cmd), self.last_result)
finally:
self.stdin = None
def wait_proc_finished(self, proc):
# wait proc finished
while True:
try:
proc.wait()
self.last_result = proc.returncode
break
except OSError, e:
if e.errno == errno.EINTR:
# Interrupted system call
continue
elif e.errno == errno.ECHILD:
# Somebody has already called waitpid
break
else:
raise
def send_signal(self, signal=signal.SIGTERM):
"""Send signal to command being executed"""
self.proc.send_signal(signal)
def send_signal_to_group(self, signal=signal.SIGTERM):
"""Send signal to the process group
of the command being executed"""
os.killpg(self.pgid, signal)
def __repr__(self):
try:
return "Cmd with pid %d" % self.pid
except AttributeError:
return "Cmd not started"