-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_methods.py
404 lines (352 loc) · 12.3 KB
/
ssh_methods.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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""
* TRANSFER_PY
* Utility to transfer the content of the gzip-ed files
* into the folder csv/.tmp to the remote host
*
* This product is protected under U.S. Copyright Law.
* Unauthorized reproduction is considered a criminal act.
* (C) 2018-2021 VDI Technologies, LLC. All rights reserved.
"""
__author__ = "Yoel Monsalve"
__date__ = "July, 2019"
__modified__ = "July, 2021"
__version__ = ""
__copyright__ = "VDI Technologies, LLC"
"""C snippet to handle signals
include <signal.h>
void sigpipe_handler(int unused)
{
}
int main(void)
{
sigaction(SIGPIPE, &(struct sigaction){sigpipe_handler}, NULL);
...
"""
"""snippet to create a new Windows console
https://stackoverflow.com/questions/6469655/how-can-i-spawn-new-shells-to-run-python-scripts-from-a-base-python-script
(option 1)
import os
os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup)
(option 2)
subprocess.popen([sys.executable, 'script.py'], creationflags = subprocess.CREATE_NEW_CONSOLE)
"""
import os
import sys
from sys import stdin, stdout, stderr, argv
import subprocess
from time import sleep
import signal
import re # regex
import shlex # quote
from helpers import is_win, is_posix
stdin_fileno = stdin.fileno()
stdout_fileno = stdout.fileno()
stderr_fileno = stderr.fileno()
def sigpipe_handler(signum, frame):
"""Custom handler to SIGPIPE: ignore
This happens when the child ends and closes the pipe, and
the signal is delivered to the parent
"""
print(f"[{os.getpid()}] W: Received SIGPIPE. Event ignored.")
def decompress_files(HOST = "", path = "", verbose = False):
if not HOST: return
if not path: return
# define SIGPIPE handler (UNIX)
if is_posix():
signal.signal(signal.SIGPIPE, sigpipe_handler)
# In Windows, we use the more suitable method subprocess, instead of the low-level
# methods fork() + spawn()
p = None
pipe = None # PIPE to talk with the child process (= subprocess.STDIN)
if verbose:
if is_win():
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags = subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
else:
if is_win():
cmd = "ssh -i .ssh/id_rsa tst@" + HOST
cmd = "cmd /C " + "\"" + cmd + "\""
p = subprocess.Popen(cmd
, stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags=subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
if not p: return
# The parent: send commands to child
pipe = p.stdin
# set permissions
s = "chmod 640 \"{:s}\"/*.csv.gz 2> /dev/null;\n".format(path)
print(s)
pipe.write(s.encode('utf-8'))
# decompress
s = "echo decompressing ...; "
s += "ls \"{:s}\"/*.csv.gz 2> /dev/null && (ls \"{:s}\"/*.csv.gz | xargs gzip -df)\n".format(path, path)
print(s)
pipe.write(s.encode('utf-8'))
# list content
s = "echo \"Done. Content of {:s}:\" && ls -l {:s}\n".format(path, path)
print(s)
pipe.write(s.encode('utf-8'));
# close & exit
#pipe.write("exit".encode('utf-8'))
pipe.write("echo -e -n \"\\nTask done. Close this windows to terminate ...\"\n".encode('utf-8'))
pipe.write("while true; do sleep 30; done".encode('utf-8'))
pipe.close()
return p
def inspect_working_directory(HOST = "", path = "", verbose = False):
if not HOST: return
if not path: return
# define SIGPIPE handler (UNIX)
if is_posix():
signal.signal(signal.SIGPIPE, sigpipe_handler)
# In Windows, we use the more suitable method subprocess, instead of the low-level
# methods fork() + spawn()
p = None
pipe = None # PIPE to talk with the child process (= subprocess.STDIN)
if verbose:
if is_win():
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags = subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
else:
if is_win():
cmd = "ssh -i .ssh/id_rsa tst@" + HOST
cmd = "cmd /C " + "\"" + cmd + "\""
p = subprocess.Popen(cmd
, stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags=subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
if not p: return
pipe = p.stdin
# set permissions
# s = "tree -d {:s} \n".format(path)
s = "tree {:s} \n".format(path) # Yoel Monsalve 07/16/2021
pipe.write(s.encode('utf-8'))
# close & exit
#pipe.write("exit".encode('utf-8'))
pipe.write("echo -e -n \"\\nTask done. Will close automatically in 10 secs ...\"\n".encode('utf-8'))
pipe.write("sleep 10\n".encode('utf-8'))
pipe.close()
return
def create_directory(HOST = "", new_path = "", mode = 0o750, create_structure = False, verbose = False):
if not HOST: return
if not new_path: return
# define SIGPIPE handler (UNIX)
if is_posix():
signal.signal(signal.SIGPIPE, sigpipe_handler)
# In Windows, we use the more suitable method subprocess, instead of the low-level
# methods fork() + spawn()
p = None
pipe = None # PIPE to talk with the child process (= subprocess.STDIN)
if verbose:
if is_win():
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags = subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
else:
if is_win():
cmd = "ssh -i .ssh/id_rsa tst@" + HOST
cmd = "cmd /C " + "\"" + cmd + "\""
p = subprocess.Popen(cmd
, stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags=subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
if not p: return
# The parent: send commands to child
print("SSH connection started, please wait ...")
pipe = p.stdin
pipe.write(f"echo \"Current content:\" && ls -l .\n".encode('utf-8'));
# creating remote directory
pipe.write(f"mkdir -p \"{new_path}\" && echo created '{new_path}' ... success.\n".encode('utf-8'))
# setting mode/perms
s = "chmod {:o} \"{:s}\" && echo mode changed to {:o} ... success.\n".format(
mode, new_path, mode)
pipe.write(s.encode('utf-8'))
if create_structure:
# creating directory structure
s = "echo \"Creating directory structure ...\"; "
pipe.write(s.encode('utf-8'))
# --> /csv
s = "echo -n \"--> creating {:s}/csv ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/csv\"; ".format(new_path)
s += "chmod 750 \"{:s}/csv\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> output
s = "echo -n \"--> creating {:s}/output/ ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/output\"; ".format(new_path)
s += "chmod 750 \"{:s}/output\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> /output/report
s = "echo -n \"--> creating {:s}/output/report ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/output/report\"; ".format(new_path)
s += "chmod 750 \"{:s}/output/report\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> /output/summary
s = "echo -n \"--> creating {:s}/output/summary ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/output/summary\"; ".format(new_path)
s += "chmod 750 \"{:s}/output/summary\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> plots
s = "echo -n \"--> creating {:s}/plots/ ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/plots\"; ".format(new_path)
s += "chmod 750 \"{:s}/plots\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> /plots/angle
s = "echo -n \"--> creating {:s}/plots/angle ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/plots/angle\"; ".format(new_path)
s += "chmod 750 \"{:s}/plots/angle\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> /plots/volt
s = "echo -n \"--> creating {:s}/plots/volt ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/plots/volt\"; ".format(new_path)
s += "chmod 750 \"{:s}/plots/volt\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
# --> /plots/unstable
s = "echo -n \"--> creating {:s}/plots/unstable ... \"; ".format(new_path)
s += "mkdir -p \"{:s}/plots/unstable\"; ".format(new_path)
s += "chmod 750 \"{:s}/plots/unstable\"; ".format(new_path)
s += "(test $? -eq 0 && echo success );"
pipe.write(s.encode('utf-8'))
#s = "echo \"Directory structure is:\"; "
#s += "tree -d {:s}".format(new_path)
#print(s)
#pipe.write(s.encode('utf-8'))
# close & exit
#pipe.write("exit".encode('utf-8'))
pipe.write("echo -e -n \"\\nTask done. Close this windows to terminate ...\"\n".encode('utf-8'))
pipe.write("while true; do sleep 30; done".encode('utf-8'))
pipe.close()
def run_app(HOST = "", working_dir = "", verbose = False):
if not HOST: return
if not working_dir: return
# define SIGPIPE handler (UNIX)
if is_posix():
signal.signal(signal.SIGPIPE, sigpipe_handler)
# In Windows, we use the more suitable method subprocess, instead of the low-level
# methods fork() + spawn()
p = None
pipe = None # PIPE to talk with the child process (= subprocess.STDIN)
if verbose:
if is_win():
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags = subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-v", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
else:
if is_win():
cmd = "ssh -i .ssh/id_rsa tst@" + HOST
cmd = "cmd /C " + "\"" + cmd + "\""
p = subprocess.Popen(cmd
, stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, creationflags=subprocess.CREATE_NEW_CONSOLE
, close_fds=True
)
else:
p = subprocess.Popen(["ssh", "-i", ".ssh/id_rsa",
"tst@" + HOST],
stdin=subprocess.PIPE
#, stdout=sys.stdout, stderr=subprocess.STDOUT
, close_fds=True
)
if not p: return
pipe = p.stdin
# set permissions
s = "./run {:s} \n".format(working_dir)
pipe.write(s.encode('utf-8'))
# close & exit
#pipe.write("exit".encode('utf-8'))
#pipe.write("echo -e -n \"\\nTask done. Will close automatically in 10 secs ...\"\n".encode('utf-8'))
#pipe.write("sleep 10\n".encode('utf-8'))
pipe.write("echo -e -n \"\\nTask done. Close this windows to terminate ...\"\n".encode('utf-8'))
pipe.write("while true; do sleep 30; done".encode('utf-8'))
pipe.close()
return
def test():
"""Test code"""
HOST = "54.38.79.195"
new_dir = "2021S_2"
#p =create_directory(HOST, new_dir, 0o750, create_structure = True)
#p = decompress_files(HOST, new_dir + '/csv')
#p = inspect_working_directory(HOST, new_dir)
p = run_app(HOST, new_dir)
exit(0)
if __name__ == "__main__":
test()