forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsshClient.py
More file actions
214 lines (199 loc) · 8.12 KB
/
Copy pathsshClient.py
File metadata and controls
214 lines (199 loc) · 8.12 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from paramiko import (BadHostKeyException,
AuthenticationException,
SSHException,
SSHClient,
AutoAddPolicy,
Transport,
SFTPClient)
import socket
import time
from marvin.cloudstackException import (
internalError,
GetDetailExceptionInfo
)
import contextlib
import logging
from marvin.codes import (
SUCCESS, FAILED, INVALID_INPUT
)
class SshClient(object):
'''
@Desc : SSH Library for Marvin.
Facilitates SSH,SCP services to marvin users
@Input: host: Host to connect
port: port on host to connect
user: Username to be used for connecting
passwd: Password for connection
retries and delay applies for establishing connection
timeout : Applies while executing command
'''
def __init__(self, host, port, user, passwd, retries=60, delay=10,
log_lvl=logging.DEBUG, keyPairFiles=None, timeout=10.0):
self.host = None
self.port = 22
self.user = user
self.passwd = passwd
self.keyPairFiles = keyPairFiles
self.ssh = SSHClient()
self.ssh.set_missing_host_key_policy(AutoAddPolicy())
self.logger = logging.getLogger('sshClient')
self.retryCnt = 0
self.delay = 0
self.timeout = 3.0
ch = logging.StreamHandler()
ch.setLevel(log_lvl)
self.logger.addHandler(ch)
# Check invalid host value and raise exception
# Atleast host is required for connection
if host is not None and host != '':
self.host = host
if retries is not None and retries > 0:
self.retryCnt = retries
if delay is not None and delay > 0:
self.delay = delay
if timeout is not None and timeout > 0:
self.timeout = timeout
if port is not None and port >= 0:
self.port = port
if self.createConnection() == FAILED:
raise internalError("SSH Connection Failed")
def execute(self, command):
stdin, stdout, stderr = self.ssh.exec_command(command)
output = stdout.readlines()
errors = stderr.readlines()
results = []
if output is not None and len(output) == 0:
if errors is not None and len(errors) > 0:
for error in errors:
results.append(error.rstrip())
else:
for strOut in output:
results.append(strOut.rstrip())
self.logger.debug("{Cmd: %s via Host: %s} {returns: %s}" %
(command, str(self.host), results))
return results
def createConnection(self):
'''
@Name: createConnection
@Desc: Creates an ssh connection for
retries mentioned,along with sleep mentioned
@Output: SUCCESS on successful connection
FAILED If connection through ssh failed
'''
ret = FAILED
except_msg = ''
while self.retryCnt >= 0:
try:
self.logger.debug("====Trying SSH Connection: Host:%s User:%s\
Port:%s RetryCnt:%s===" %
(self.host, self.user, str(self.port),
str(self.retryCnt)))
if self.keyPairFiles is None:
self.ssh.connect(hostname=self.host,
port=self.port,
username=self.user,
password=self.passwd,
timeout=self.timeout,
allow_agent=False)
else:
self.ssh.connect(hostname=self.host,
port=self.port,
username=self.user,
password=self.passwd,
key_filename=self.keyPairFiles,
timeout=self.timeout,
look_for_keys=False
)
self.logger.debug("===SSH to Host %s port : %s SUCCESSFUL==="
% (str(self.host), str(self.port)))
ret = SUCCESS
break
except BadHostKeyException as e:
except_msg = GetDetailExceptionInfo(e)
except AuthenticationException as e:
except_msg = GetDetailExceptionInfo(e)
except SSHException as e:
except_msg = GetDetailExceptionInfo(e)
except socket.error as e:
except_msg = GetDetailExceptionInfo(e)
except Exception as e:
except_msg = GetDetailExceptionInfo(e)
finally:
if self.retryCnt == 0 or ret == SUCCESS:
break
if except_msg != '':
self.logger.\
exception("SshClient: Exception under "
"createConnection: %s" % except_msg)
self.retryCnt -= 1
time.sleep(self.delay)
return ret
def runCommand(self, command):
'''
@Name: runCommand
@Desc: Runs a command over ssh and
returns the result along with status code
@Input: command to execute
@Output: 1: status of command executed.
SUCCESS : If command execution is successful
FAILED : If command execution has failed
2: stdin,stdout,stderr values of command output
'''
ret = {"status": FAILED, "stdin": None, "stdout": None,
"stderr": INVALID_INPUT}
if command is None or command == '':
return ret
try:
status_check = 1
stdin, stdout, stderr = self.ssh.\
exec_command(command, timeout=self.timeout)
if stdout is not None:
status_check = stdout.channel.recv_exit_status()
if status_check == 0:
ret["status"] = SUCCESS
ret["stdout"] = stdout.readlines()
if stderr is not None:
ret["stderr"] = stderr.readlines()
except Exception as e:
ret["stderr"] = GetDetailExceptionInfo(e)
self.logger.exception("SshClient: Exception under runCommand :%s" %
GetDetailExceptionInfo(e))
finally:
self.logger.debug(" Host: %s Cmd: %s Output:%s" %
(self.host, command, str(ret)))
return ret
def scp(self, srcFile, destPath):
transport = Transport((self.host, int(self.port)))
transport.connect(username=self.user, password=self.passwd)
sftp = SFTPClient.from_transport(transport)
try:
sftp.put(srcFile, destPath)
except IOError as e:
raise e
def __del__(self):
self.close()
def close(self):
if self.ssh is not None:
self.ssh.close()
self.ssh = None
if __name__ == "__main__":
with contextlib.closing(SshClient("127.0.0.1", 22, "root",
"asdf!@34")) as ssh:
ret = ssh.runCommand("ls -l")
print ret