-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathssh_tool.py
More file actions
131 lines (104 loc) · 3.23 KB
/
ssh_tool.py
File metadata and controls
131 lines (104 loc) · 3.23 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
import subprocess
import time
class ssh_tool:
def __init__(self, username, ip_address, sshkey=None):
self.rem_username = username
self.ip = ip_address
self.sshkey = sshkey
def ssh(self, command, test=True, option=None, output=False, silent=False):
if self.sshkey is None:
keyls = []
else:
keyls = ["-i", self.sshkey]
call_list = (
["ssh"]
+ keyls
+ [
"-o",
"StrictHostKeyChecking=no",
"-o",
"ConnectTimeout=10",
"-o",
"BatchMode=yes",
]
)
if option:
call_list.extend(["-o", option])
call_list.extend([self.rem_username + "@" + self.ip, command])
print("ssh_tool: " + " ".join(call_list))
stdout = ""
ret = -1
if output or silent:
try:
stdout = subprocess.check_output(call_list, stderr=subprocess.STDOUT)
ret = 0
except subprocess.CalledProcessError as e:
ret = e.returncode
print(e)
print(stdout)
else:
ret = subprocess.call(call_list)
if ret != 0:
print(stdout)
# By default, it is not ok to fail
if test:
assert ret == 0
if output:
return stdout
return ret
def check_access(self):
# Check if the machine is accessible:
for _ in range(30):
out = self.ssh("uname -a", test=False)
if out == 0:
print(f"Successfully connected to {self.ip}")
return True
print(f"Failed to connect to {self.ip}, Retry in 20 seconds")
time.sleep(20)
return False
def scp_to(self, file_path_local, file_path_remote="", test=True):
if self.sshkey is None:
keyls = []
else:
keyls = ["-i", self.sshkey]
call_list = (
["scp", "-r"]
+ keyls
+ [
"-o",
"StrictHostKeyChecking=no",
"-o",
"BatchMode=yes",
file_path_local,
self.rem_username + "@" + self.ip + ":" + file_path_remote,
]
)
print("ssh_tool: " + " ".join(call_list))
ret = subprocess.call(call_list)
# By default, it is not ok to fail
if test:
assert ret == 0
return ret
def scp_from(self, file_path_remote, file_path_local=".", test=True):
if self.sshkey is None:
keyls = []
else:
keyls = ["-i", self.sshkey]
call_list = (
["scp", "-r"]
+ keyls
+ [
"-o",
"StrictHostKeyChecking=no",
"-o",
"BatchMode=yes",
self.rem_username + "@" + self.ip + ":" + file_path_remote,
file_path_local,
]
)
print("ssh_tool: " + " ".join(call_list))
ret = subprocess.call(call_list)
# By default, it is not ok to fail
if test:
assert ret == 0
return ret