-
Notifications
You must be signed in to change notification settings - Fork 7
/
Conn.py
334 lines (293 loc) · 11.3 KB
/
Conn.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
# coding:utf-8
from ftplib import FTP
import telnetlib
import sys
import paramiko
import re
import Sundry as s
import GetConfig as gc
class FTPConn(object):
def __init__(self, strIP, intPort, strUser, strPWD, intTO):
self._host = strIP
self._port = intPort
self._username = strUser
self._password = strPWD
self._timeout = intTO
self._connected = None
self._logined = None
self._Connection = None
# self._FTPconnect()
def _FTPconnect(self):
ftp = FTP()
def _conn():
try:
ftp.connect(self._host, self._port, self._timeout)
self._connected = ftp
return True
except Exception as E:
s.ShowErr(self.__class__.__name__,
sys._getframe().f_code.co_name,
'FTP connect to "{}" failed with error:'.format(
self._host),
'"{}"'.format(E))
def _login():
try:
ftp.login(self._username, self._password)
self._logined = ftp
return True
except Exception as E:
# print(E)
s.ShowErr(self.__class__.__name__,
sys._getframe().f_code.co_name,
'FTP login to "{}" failed with error:'.format(
self._host),
'"{}"'.format(E))
if _conn():
if _login():
self._Connection = ftp
return True
def GetFile(self, strRemoteFolder, strLocalFolder, strRemoteFileName,
strLocalFileName, FTPtype='bin', intBufSize=1024):
def _getfile():
try:
ftp = self._Connection
# print(ftp.getwelcome())
ftp.cwd(strRemoteFolder)
objOpenLocalFile = open('{}/{}'.format(
strLocalFolder, strLocalFileName), "wb")
if FTPtype == 'bin':
ftp.retrbinary('RETR {}'.format(strRemoteFileName),
objOpenLocalFile.write)
elif FTPtype == 'asc':
ftp.retrlines('RETR {}'.format(strRemoteFileName),
objOpenLocalFile.write)
objOpenLocalFile.close()
ftp.cwd('/')
return True
except Exception as E:
s.ShowErr(self.__class__.__name__,
sys._getframe().f_code.co_name,
'FTP download "{}" failed with error:'.format(
self._host),
'"{}"'.format(E))
if self._Connection:
if _getfile():
return True
else:
if self._FTPconnect():
if _getfile():
return True
def PutFile(self, strRemoteFolder, strLocalFolder, strRemoteFileName,
strLocalFileName, FTPtype='bin', intBufSize=1024):
def _putfile():
try:
ftp = self._Connection
# print(ftp.getwelcome())
ftp.cwd(strRemoteFolder)
objOpenLocalFile = open('{}/{}'.format(
strLocalFolder, strLocalFileName), 'rb')
if FTPtype == 'bin':
ftp.storbinary('STOR {}'.format(strRemoteFileName),
objOpenLocalFile, intBufSize)
elif FTPtype == 'asc':
ftp.storlines('STOR {}'.format(
strRemoteFileName), objOpenLocalFile)
ftp.set_debuglevel(0)
objOpenLocalFile.close()
return True
except Exception as E:
s.ShowErr(self.__class__.__name__,
sys._getframe().f_code.co_name,
'FTP upload "{}" failed with error:'.format(
self._host),
'"{}"'.format(E))
if self._Connection:
if _putfile():
return True
else:
if self._FTPconnect():
if _putfile():
return True
def close(self):
if self._Connection:
self._Connection.quit()
self._Connection = None
class SSHConn(object):
def __init__(self, host, port, username, password, timeout):
self._host = host
self._port = port
self._timeout = timeout
self._username = username
self._password = password
self.SSHConnection = None
self._sftp = None
self.ssh_connect()
def _connect(self):
try:
objSSHClient = paramiko.SSHClient()
objSSHClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
objSSHClient.connect(self._host, port=self._port,
username=self._username,
password=self._password,
timeout=self._timeout)
self.SSHConnection = objSSHClient
except:
pass
# def download(self, remotepath, localpath):
# def _download():
# if self._sftp is None:
# self._sftp = self.SSHConnection.open_sftp()
# self._sftp.get(remotepath, localpath)
# try:
# _download()
# except AttributeError as E:
# print(__name__, E)
# print('Download Failed,Not Connect to {}'.format(self._host))
# return None
# else:
# print(__name__, E)
# print('Download Failed ...')
# def upload(self, localpath, remotepath):
# def _upload():
# if self._sftp is None:
# self._sftp = self.SSHConnection.open_sftp()
# self._sftp.put(localpath, remotepath)
# try:
# _upload()
# except AttributeError as E:
# print(__name__, E)
# print('Upload Failed,Not Connect to {}'.format(self._host))
# return None
# else:
# print(__name__, E)
# print('Upload Failed ...')
def ssh_connect(self):
self._connect()
if not self.SSHConnection:
print('Connect retry for SAN switch "%s" ...' % self._host)
self._connect()
def exctCMD(self, command):
def GetRusult():
stdin, stdout, stderr = self.SSHConnection.exec_command(command)
data = stdout.read()
if len(data) > 0:
# print(data.strip())
return data
err = stderr.read()
if len(err) > 0:
print('''Excute command "{}" failed on "{}" with error:
"{}"'''.format(command, self._host, err.strip()))
def _return(strResult):
if strResult:
return strResult
# else:
# s.ShowErr(self.__class__.__name__,
# sys._getframe().f_code.co_name,
# 'Execute Command "{}" Failed with Error:'.format(
# self._host),
# E)
if self.SSHConnection:
output = _return(GetRusult())
if output:
return output
def close(self):
if self.ssh_connect:
self.ssh_connect.close()
class HAAPConn(object):
def __init__(self, strIP, intPort, strPWD, intTO):
self._host = strIP
self._port = intPort
self._password = strPWD
self._timeout = intTO
self._product = gc.General().get_PRODUCT()
self._strLoginPrompt = 'Enter password'
self._strMainMenuPrompt = 'Coredump Menu'
self._strCLIPrompt = 'CLI>'
self._strAHPrompt = 'AH_CLI>'
self._strCLIConflict = 'Another session owns the CLI'
self.Connection = None
self.telnet_connect()
def _connect(self):
try:
objTelnetConnect = telnetlib.Telnet(
self._host, self._port, self._timeout)
objTelnetConnect.read_until(
self._strLoginPrompt.encode(encoding="utf-8"), timeout=1)
objTelnetConnect.write(self._password.encode(encoding="utf-8"))
objTelnetConnect.write(b'\r')
objTelnetConnect.read_until(
self._strMainMenuPrompt.encode(encoding="utf-8"), timeout=1)
self.Connection = objTelnetConnect
return True
except Exception as E:
s.ShowErr(self.__class__.__name__,
sys._getframe().f_code.co_name,
'Telnet connect to "{}" failed with error:'.format(
self._host),
'"{}"'.format(E))
def _connect_retry(self):
if self.Connection:
return True
else:
print('Connect retry for engine "%s" ...' % self._host)
self._connect()
def telnet_connect(self):
if not self._connect():
self._connect_retry()
def get_connection_status(self):
if self.Connection:
return True
else:
return False
def is_AH(self):
strPrompt = self.exctCMD('')
if strPrompt:
if self._strAHPrompt in strPrompt:
strVPD = self.exctCMD('vpd')
reAHNum = re.compile(r'Alert:\s*(\d*)')
objReAHNum = reAHNum.search(strVPD)
return int(objReAHNum.group(1))
else:
return 0
def exctCMD(self, strCommand):
CLI = self._strCLIPrompt.encode(encoding="utf-8")
CLI_Conflict = self._strCLIConflict.encode(encoding="utf-8")
def get_result():
self.Connection.write(
strCommand.encode(encoding="utf-8") + b'\r')
strResult = str(self.Connection.read_until(
CLI, timeout=2).decode())
if self._strCLIPrompt in strResult:
return strResult
def execute_at_CLI():
# Confirm is CLI or Not
if self.Connection:
self.Connection.write(b'\r')
strEnterOutput = self.Connection.read_until(CLI, timeout=1)
if CLI in strEnterOutput:
return get_result()
elif self._product.encode(encoding="utf-8") in strEnterOutput:
self.Connection.write('7')
str7Output = self.Connection.read_until(CLI, timeout=1)
if CLI in str7Output:
return get_result()
elif CLI_Conflict in str7Output:
self.Connection.write('y')
strConfirmCLI = self.Connection.read_until(CLI, timeout=1)
if CLI in strConfirmCLI:
return get_result()
if self.Connection:
return execute_at_CLI()
# else:
# if self._connect():
# return execute_at_CLI()
# else:
# print('Please Check Telnet Connection to "{}" \n\n'.format(
# self._host))
def Close(self):
if self.Connection:
self.Connection.close()
connection = property(
get_connection_status, doc="Get HAAPConn instance's connection")
if __name__ == '__main__':
pass