· 9 years ago · Jan 12, 2017, 02:16 PM
1# Test Ip's below #
2#
3# 10.45.4.141
4# 10.45.4.192
5# 10.45.4.93
6#####################
7#
8# Add later
9# If value is blank when it goes to display it
10# point out in log that the value is empty
11#####################
12
13
14import errno
15import os
16import os.path
17import sys
18import cmd
19import paramiko
20import msvcrt as m
21import time
22import logging
23import subprocess
24import smtplib
25import sys
26from email.mime.multipart import MIMEMultipart
27from email.mime.text import MIMEText
28from email.mime.application import MIMEApplication
29from PIL import Image, ImageFilter
30
31global username, password, port, host, SERIAL, Version_, _WorkDir_, source, destination, UtilHome
32password = "ew3_llc" #could prompt later
33username = "root" #could prompt later
34port = 22
35host = ''
36Version_ = ''
37Version_App = ''
38Version_System = ''
39SERIAL = ''
40source = 'SoftwareUpgrade'
41destination = '/tmp/updatesw/'
42UtilHome = os.getcwd()
43cmdOUTPUT = ""
44
45# Generic Log file line use
46# logging.info('[' + time.strftime("%H:%M") + ']|> ')
47
48#####################################
49# #
50# -Defining Functions- #
51# #
52#####################################
53def PrintBox(message):
54 print('\n__________________________________\n')
55 print(' ' + message)
56 print('\n__________________________________\n')
57
58def Log(message):
59 logging.info(' _____________[' + time.strftime("%H:%M") + ']___________')
60 logging.info(']|> ' + message)
61 logging.info(' ____________________________________________________________\n')
62 # logging.info('\n')
63
64def FindType(TYPE):
65 Log(TYPE + ' is ' + type(TYPE))
66
67
68def CreateOSFolder(Folders):
69 for elem in Folders:
70 if not os.path.exists(elem):
71 logging.info('[' + time.strftime("%H:%M") + ']|> creating ' + elem)
72 os.mkdir(elem)
73def Clear():
74 Log('Running Clear()...')
75 os.system(['clear','cls'][os.name == 'nt'])
76
77def wait():
78 Log('waiting...')
79 print('\n Press any key to continue..')
80 m.getch()
81 Clear()
82
83
84def HomeFolder():
85 # May go away with use of UtilHome
86 Log('moving to homefolder')
87 os.chdir(UtilHome)
88 Log('current Folder : ' + UtilHome)
89
90def PrintDirs():
91 Log('Current OSdir - ' + os.getcwd() + '\n Current SFTPdir ' + sftp.getcwd() + '\n Current UtilHome : ' + UtilHome)
92
93def ClearHost():
94 Log('cleaning host information..')
95 global host, SERIAL, Version_App, Version_System
96 host = ''
97 SERIAL = ''
98 Version_App = ''
99 Version_System = ''
100 filepath = ''
101
102def Reboot():
103 global host, SERIAL, Version_App, Version_System
104 Log('Rebooting..')
105 PrintBox('Please press any button\n to reboot Nexgen')
106 m.getch()
107 cmd = 'reboot'
108 stdin, stdout, stderr = ssh.exec_command(cmd)
109 _reboot = stdout.read().strip().decode(encoding='utf-8')
110 stdin, stdout, stderr = ssh.exec_command('cmd')
111 ClearHost()
112 Clear()
113
114def TestPing():
115 Log('entered test ping()....')
116 global host
117 print('contacting ' + host + ' ...')
118 Log('contacting ' + host)
119 ping_result = subprocess.Popen(["ping.exe",host],stdout = subprocess.PIPE).communicate()[0]
120 if (b'unreachable' in ping_result):
121 Log('host unreachable')
122 print('\nHost unreachable, please try again')
123 wait()
124 GetHost()
125 elif (b'timed out.' in ping_result):
126 Log('host unreachable')
127 PrintBox('connection timed out, please try again')
128 wait()
129 Clear()
130 GetHost()
131 elif (b'failed' in ping_result):
132 Log('host unreachable')
133 PrintBox('ping failed, please try again')
134 wait()
135 Clear()
136 GetHost()
137 else:
138 Log('host online!')
139 PrintBox('host online')
140 ConnectSSH()
141
142def GetHost():
143 HomeFolder()
144 global host
145 host = input('\nPlease Enter IP Address: ')
146 print('The IP Address has been changed to : ' + host + '\n')
147 Log(' > Entered GetHost() \n host : ' + host)
148 TestPing()
149 WifiCheck()
150 Clear()
151
152def CheckSSH():
153 Clear()
154 Log('checking for host from CheckSSH')
155 if host == '':
156 logging.info('no host found, asking for host IP')
157 PrintBox('Need IP Address First!')
158 GetHost()
159
160def KillAll():
161 Log('entered KillAll()...')
162 CheckSSH()
163 Clear()
164 PrintBox('Working on SD card....')
165 Log('Starting Format_SD ..')
166 cmd = 'tail /etc/inittab'
167 stdin, stdout, stderr = ssh.exec_command(cmd)
168 AppSearch = stdout.read().strip().decode(encoding='utf-8')
169
170 Log('inittab info below... \n\n' + AppSearch + '\n')
171 if '#za' in AppSearch:
172 Log('#za already commented out')
173 else:
174 Log('commenting za out')
175 cmd = 'sed -i s/za:/#za:/ /etc/inittab'
176 stdin, stdout, stderr = ssh.exec_command(cmd)
177
178 try:
179 time.sleep(5)
180 finally:
181 print('')
182
183 if '#zb' in AppSearch:
184 Log('#zb already commented out')
185 else:
186 Log('commenting zb out')
187 cmd = 'sed -i s/zb:/#zb:/ /etc/inittab'
188 stdin, stdout, stderr = ssh.exec_command(cmd)
189
190 time.sleep(5)
191
192 if '#zc' in AppSearch:
193 Log('#zc already commented out')
194 else:
195 Log('commenting zc out')
196 cmd = 'sed -i s/zc:/#zc:/ /etc/inittab'
197 stdin, stdout, stderr = ssh.exec_command(cmd)
198
199 try:
200 time.sleep(5)
201 finally:
202 print('')
203
204 if '#zd' in AppSearch:
205 Log('#z already commented out')
206 else:
207 Log('commenting zd out')
208 cmd = 'sed -i s/zd:/#zd:/ /etc/inittab'
209 stdin, stdout, stderr = ssh.exec_command(cmd)
210
211 try:
212 time.sleep(5)
213 finally:
214 print('')
215
216 stdin, stdout, stderr = ssh.exec_command('init q')
217
218 time.sleep(5)
219
220 Log('stopping mclient ..')
221 stdin, stdout, stderr = ssh.exec_command('sh /etc/init.d/mclientd stop')
222
223 try:
224 time.sleep(5)
225 finally:
226 print('')
227
228 Log('stopping syslog ..')
229 stdin, stdout, stderr = ssh.exec_command('sh /etc/init.d/syslog stop')
230
231 try:
232 time.sleep(5)
233 finally:
234 print('')
235
236 cmd = 'mount'
237 stdin, stdout, stderr = ssh.exec_command(cmd)
238 MOUNTlog = stdout.read().strip().decode(encoding='utf-8')
239 Log('Mount info BEFORE unmount below... \n\n' + MOUNTlog + '\n')
240
241def ReviveAll():
242 Log('running sed, then will output contents of file')
243 print('changing from vfat -> auto...')
244 cmd = 'sed -i s/vfat/auto/ /etc/fstab'
245 stdin, stdout, stderr = ssh.exec_command(cmd)
246
247 time.sleep(4)
248
249 cmd = 'cat /etc/fstab'
250 stdin, stdout, stderr = ssh.exec_command(cmd)
251 FSTABlog = stdout.read().strip().decode(encoding='utf-8')
252 Log('FSTAB BELOW>..\n\n: ' + FSTABlog + '\n')
253
254 PrintBox('restoring inittab file..')
255 cmd = 'tail /etc/inittab'
256 stdin, stdout, stderr = ssh.exec_command(cmd)
257 AppSearch = stdout.read().strip().decode(encoding='utf-8')
258
259 #will make function/array in future iteration
260 if '#za' in AppSearch:
261 Log('un-commenting za out')
262 cmd = 'sed -i s/#za:/za:/ /etc/inittab'
263 stdin, stdout, stderr = ssh.exec_command(cmd)
264 else:
265 Log('za not commented out')
266
267 time.sleep(5)
268
269 if '#zb' in AppSearch:
270 Log('un-commenting zb out')
271 cmd = 'sed -i s/#zb:/zb:/ /etc/inittab'
272 stdin, stdout, stderr = ssh.exec_command(cmd)
273 else:
274 Log('zb not commented out')
275
276 time.sleep(5)
277
278 if '#zc' in AppSearch:
279 Log('un-commenting zc out')
280 cmd = 'sed -i s/#zc:/zc:/ /etc/inittab'
281 stdin, stdout, stderr = ssh.exec_command(cmd)
282 else:
283 Log('zc not commented out')
284
285 time.sleep(5)
286
287 if '#zd' in AppSearch:
288 Log('un-commenting zd out')
289 cmd = 'sed -i s/#zd:/zd:/ /etc/inittab'
290 stdin, stdout, stderr = ssh.exec_command(cmd)
291 else:
292 Log('zd not commented out')
293
294 time.sleep(5)
295 cmd = 'mount'
296 stdin, stdout, stderr = ssh.exec_command(cmd)
297 MOUNTlog = stdout.read().strip().decode(encoding='utf-8')
298 Log('Mount info BEFORE unmount below... \n\n' + MOUNTlog + '\n')
299
300def Fdisk():
301 KillAll()
302 Log('Starting Format_SD ..\n running fdisk ..')
303 cmd = '(echo d; echo n; echo p; echo 1; echo ; echo ; echo w;) | fdisk /dev/mmcblk0'
304 stdin, stdout, stderr = ssh.exec_command(cmd)
305
306
307def MKFS():
308 Clear()
309 Log('Starting Format_SD ..\n umounting ..')
310 print('making filesystem, takes about 85 seconds...')
311 cmd = 'mkfs.ext3 /dev/mmcblk0p1'
312 stdin, stdout, stderr = ssh.exec_command(cmd)
313 time.sleep(85)
314 ReviveAll()
315
316def CheckSD():
317 Log('entered CheckSD().....')
318 cmd = "mount | grep '/dev/mmcblk0p1'"
319 stdin, stdout, stderr = ssh.exec_command(cmd)
320 SDreults = stdout.read().strip().decode(encoding='utf-8')
321 if 'var/permalog' in SDreults:
322 Log('\n SD card check successful')
323 PrintBox('SD card check successful!')
324 wait()
325 else:
326 Log('\n SD card bad')
327 PrintBox('App Version is... ' + Version_App + '\n press any key to continue\n')
328 m.getch()
329 if '10.0.6' in Version_App:
330 Log('running mkfs command..')
331 PrintBox('SD Card bad, fixing!\n\n Making filesystem...\n')
332 Fdisk()
333 MKFS()
334 PrintBox('SD card repaired, preparing to reboot')
335 time.sleep(10)
336 Reboot()
337 else:
338 #PrintBox('unit not upgraded to 10.0.6, continuing')
339 time.sleep(5)
340
341def SDFix():
342 Log('entered SDFix()...')
343 KillAll()
344 cmd = 'umount -l /dev/mmcblk0p1'
345 stdin, stdout, stderr = ssh.exec_command(cmd)
346 time.sleep(5)
347
348 logging.info('[' + time.strftime("%H:%M") + ']|> running mkfs...')
349 print('making filesystem...\n This will take about 85 seconds.. \n')
350 cmd = 'mkfs.ext3 /dev/mmcblk0p1'
351 stdin, stdout, stderr = ssh.exec_command(cmd)
352 time.sleep(85)
353
354 cmd = 'mount /dev/mmcblk0p1'
355 stdin, stdout, stderr = ssh.exec_command(cmd)
356 time.sleep(5)
357 ReviveAll()
358
359def ConnectSSH():
360 Clear()
361 CheckSSH()
362 Log('Connecting to host...')
363 print('Connecting to ' + host)
364 global ssh, sftp
365 ssh = paramiko.SSHClient()
366 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
367 ssh.connect(host, username = username, password = password)
368 print(' Connected to ' + host)
369 logging.info('connected to host (' + host + ')')
370 sftp = ssh.open_sftp()
371 GetVersion()
372 GetSerial()
373
374
375def ChangeSerial():
376 Log('Changing Serial...')
377 sftp.chdir('/etc/unique/')
378 try:
379 sftp.stat('SERIAL')
380 except IOError as e:
381 print()
382 else:
383 sftp.remove('SERIAL')
384 HomeFolder()
385 os.chdir('temp/unique')
386 print('_______________________________________\n')
387 NewSerial = input('Please enter the correct/updated Serial number and press the enter key: \n\n'
388 'New Serial: ')
389 f = open('SERIAL', 'w')
390 f.write(NewSerial)
391 f.close()
392 sftp.put('SERIAL','SERIAL')
393 LocalClean()
394 print('Serial Number updated, checking Serial Number on device..')
395 print('_______________________________________\n')
396 Log('serial set to ' + NewSerial)
397 ConnectSSH()
398
399def SendCMD(cmd):
400 global cmdOUTPUT
401 Log('sending command.. ' + cmd)
402 stdin, stdout, stderr = ssh.exec_command(cmd)
403 cmdOUTPUT = stdout.read().strip().decode(encoding='utf-8')
404 Log('output of ' + cmd + 'is below.. \n' + cmdOUTPUT)
405 #print('output of ' + cmd + 'is below.. \n' + cmdOUTPUT)
406 #wait()
407 return cmdOUTPUT
408
409
410def GetSerial():
411 global SERIAL
412 sftp.chdir('/etc/unique')
413 SERIAL = SendCMD('head /etc/unique/SERIAL')
414 Log('Current Serial: ' + SERIAL)
415 print('Please confirm that the serial number below \nmatches the label on the back of the device \n')
416 print("Serial: " + SERIAL + '\n')
417 _serialanswer_ = input('Is this serial correct?(Y/N) ')
418 if _serialanswer_ == b'N':
419 Log('user specified serial is incorrect')
420 ChangeSerial()
421 elif _serialanswer_ == 'n':
422 Log('user specified serial is incorrect')
423 ChangeSerial()
424 else:
425 Log('user specified serial is correct')
426 print()
427
428def GetVersion():
429 global Version_App, Version_System
430 SendCMD("ipkg list_installed | grep pts150-application")
431 Version = cmdOUTPUT
432 Version_App = Version[Version.find("pts150-application - ") + 20:Version.find(" - Application")]
433 global Version_
434 SendCMD("ipkg list_installed | grep pts150-system")
435 Version = cmdOUTPUT
436 Version_System = Version[Version.find("pts150-system - ") + 16:Version.find(" - System")]
437 PrintBox('Application version is :' + Version_App)
438 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
439
440
441def GetTemp():
442 CheckSSH()
443 global Temp
444 SendCMD("grep -Eo 'Calibration Temperature Offset C100ths</comment><value>-*[0-9]+' /etc/ptsenv/THERM.cfg")
445 Temp = cmdOUTPUT
446 TempValue = Temp[55:]
447 if TempValue == "":
448 print('no value found')
449 SendCMD("head -10 /etc/ptsenv/THERM.cfg | tail -1 | grep value")
450 Temp = cmdOUTPUT
451 TempValue = Temp[7:]
452 if '</value>' in TempValue:
453 Log('removing </value> from TempValue')
454 TempValue = TempValue.replace('</value>','')
455 else:
456 print('')
457 else:
458 print('')
459 PrintBox('The set point value is: ' + TempValue)
460 Log('Set Value is ' + TempValue)
461 wait()
462
463def Remove(RMfiles,path):
464 CheckSSH()
465 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
466 logging.info('[' + time.strftime("%H:%M") + ']|> Running Remove(): ')
467 for elem in RMfiles:
468 print('\n___________________________')
469 print('Looking for ' + elem + ' .....')
470 if elem in sftp.listdir(path):
471 print('Removing ' + elem + '....')
472 print('___________________________\n')
473 logging.info('[' + time.strftime("%H:%M") + ']|> removing following files :')
474 logging.info('[' + time.strftime("%H:%M") + ']|> ' + elem)
475 sftp.remove(path + elem)
476 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
477
478def RemoveRemoteDir():
479 CheckSSH()
480 ConnectSSH()
481 PrintDirs()
482 Log('Running RemoveRemoteDir() ')
483 for filename in sftp.listdir(destination):
484 filepath = os.path.join(destination, filename)
485 print('removing ' + filename)
486 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
487 sftp.remove(filepath)
488 print('\n removing ' + destination)
489 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + destination)
490 sftp.rmdir(destination)
491 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
492
493def RemoveFactory():
494 CheckSSH()
495 Log('Running RemoveFactory()')
496 RMfiles = ['FACTORY']
497 Remove(RMfiles,'/etc/ptsenv/')
498
499def RemoveCONFIGsav():
500 CheckSSH()
501 Log('Running RemoveCONFIGsav()')
502 RMfiles = ['CONFIG.sav']
503 Remove(RMfiles,'/etc/ptsenv/')
504
505
506def CheckUpdateSW():
507 CheckSSH()
508 Log('Running CheckUpdateSW() ')
509 print(' Checking for (' + destination + ')\n')
510 try:
511 sftp.stat(destination)
512 except IOError as e:
513 if 'No such file' in str(e):
514 print('update folder not found..')
515 print('creating updatesw directory')
516 logging.info('[' + time.strftime("%H:%M") + ']|> creating /tmp/updatesw')
517 sftp.mkdir('/tmp/updatesw')
518 print('proceeding to upgrade..')
519 Upgrade()
520 else:
521 print('Folder already exists..\n')
522 print('removing old folder')
523 RemoveRemoteDir()
524 print('folder removed\n')
525 print('removing host IP from utility..')
526 host = ''
527 print('(host value should be blank)')
528 print('host : ' + host)
529 print('going back to menu...')
530 PrintBox('unit already had update folder \nyou are about to return to menu \n please choose upgrade again')
531 Clear()
532 CheckUpdateSW()
533 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
534
535
536def WindsorBackup():
537 global SERIAL
538 MapLDrive()
539 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
540 logging.info('[' + time.strftime("%H:%M") + ']|> Entered WindsorBackup')
541 os.chdir('L:\\')
542 PrintDirs()
543
544 if os.path.exists(str(SERIAL)):
545 logging.info('[' + time.strftime("%H:%M") + ']|> ' + str(SERIAL) + ' is there!')
546 else:
547 CreateOSFolder([str(SERIAL)])
548 logging.info('[' + time.strftime("%H:%M") + ']|> created ' + str(SERIAL))
549
550 TimeStamp = time.strftime("%m_%d_%Y")
551 Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
552
553 if os.path.exists(Ldrive):
554 logging.info('[' + time.strftime("%H:%M") + ']|> ' + Ldrive + 'was not found, will use hour and minute')
555 #Ldrive = str(SERIAL)+'\\' +
556 #time.strftime("%Y-%m-%d_%H-%M")+'\Pre_Wipe'
557 TimeStamp = time.strftime("%m_%d_%Y[%H-%M]")
558 Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
559 CreateOSFolder([Ldrive])
560 logging.info('[' + time.strftime("%H:%M") + ']|> new Ldrive .. ' + Ldrive)
561 else:
562 logging.info('[' + time.strftime("%H:%M") + ']|>' + Ldrive + 'was not found, creating it')
563 CreateOSFolder([Ldrive])
564 logging.info('[' + time.strftime("%H:%M") + ']|> creating rest of folders for backup')
565
566 CreateOSFolder([Ldrive + '\Windsor_Backup',
567 Ldrive + '\Windsor_Backup\etc', Ldrive + '\Windsor_Backup\etc\ptsenv', Ldrive + r'\Windsor_Backup\etc\unique',
568 Ldrive + '\Windsor_Backup\\var', Ldrive + '\Windsor_Backup\\var\permalog',
569 Ldrive + '\Windsor_Backup\home', Ldrive + '\Windsor_Backup\home\localdata'])
570
571 PrintBox('Utility will now begin transferring files\n from unit to network drive...')
572 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
573 logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to : ' + Ldrive)
574 logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
575
576 sftp.chdir('/etc/')
577 os.chdir(Ldrive + '\Windsor_Backup\etc')
578 path = 'ptsenv/'
579 PrintDirs()
580
581 print('Backing up ptsenv folder...')
582 for filename in sftp.listdir('ptsenv'):
583 if filename == 'BATTERY.log':
584 logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
585 cmd = 'rm ' + filename
586 stdin, stdout, stderr = ssh.exec_command(cmd)
587 elif filename != 'wpa_supplicant.d':
588 if filename != 'BATTERY.log':
589 filepath = os.path.join(path, filename)
590 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
591 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
592 sftp.get(filepath, filepath)
593
594 path = 'unique/'
595 PrintDirs()
596 print('Backing up unique folder....')
597 for filename in sftp.listdir('unique'):
598 filepath = os.path.join(path, filename)
599 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
600 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
601 sftp.get(filepath, filepath)
602 os.chdir('..')
603
604 sftp.chdir('/home/')
605 os.chdir('home')
606 PrintDirs()
607 path = 'localdata/'
608 print('Backing up localdata folder....')
609 for filename in sftp.listdir('localdata'):
610 if 'PTS' in filename:
611 filepath = os.path.join(path, filename)
612 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
613 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
614 sftp.get(filepath, filepath)
615 os.chdir('..')
616
617 sftp.chdir('/var/')
618 os.chdir('var')
619 path = 'permalog/'
620 PrintDirs()
621
622 print('Backing up permalog folder....')
623 for filename in sftp.listdir('permalog'):
624 if filename == 'lost+found':
625 print('Removing lost+found')
626 logging.info('[' + time.strftime("%H:%M") + ']|> removing ' + path + 'lost+found')
627 sftp.rmdir(path + 'lost+found')
628 else:
629 if filename != 'Templates':
630 if filename != 'System Volume Information':
631 filepath = os.path.join(path, filename)
632 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
633 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
634 sftp.get(filepath, filepath)
635
636 os.chdir('..')
637 wait()
638 logging.info('[' + time.strftime("%H:%M") + ']|> finished pre wipe backup...')
639 logging.info('[' + time.strftime("%H:%M") + ']|> removing files...')
640 Clear()
641
642
643def GuiFileCheck():
644 Log('Checking for PTS GUI')
645 cmd = 'ls /etc/ptsenv/'
646 stdin, stdout, stderr = ssh.exec_command(cmd)
647 GuiFileSearch = stdout.read().strip().decode(encoding='utf-8')
648 Log('contents of GuiFileSearch below... \n\n' + GuiFileSearch)
649 if 'pts150gui2.ini' in GuiFileSearch:
650 pass
651 else:
652 Log('pts150gui.ini not found in etc/petsenv/, creating file')
653 stdin, stdout, stderr = ssh.exec_command("echo '[wifi]' >> /etc/ptsenv/pts150gui.ini")
654 stdin, stdout, stderr = ssh.exec_command("UseWifi=false >> /etc/ptsenv/pts150gui.ini")
655
656
657def WifiNo():
658 GuiFileCheck()
659 Log('Setting Wifi to False')
660 cmd = 'cat /etc/ptsenv/pts150gui.ini'
661 stdin, stdout, stderr = ssh.exec_command(cmd)
662 WifiSearch = stdout.read().strip().decode(encoding='utf-8')
663 Log('contents of pts150gui below... \n\n' + WifiSearch)
664 if 'UseWifi=false' in WifiSearch:
665 Log('WiFi already false')
666 PrintBox('WiFI already enabled')
667 elif 'UseWifi=true' in WifiSearch:
668 Log('changing UseWifi to true..')
669 cmd = "sed -i s/UseWifi=true/UseWifi=false/ /etc/ptsenv/pts150gui.ini"
670 stdin, stdout, stderr = ssh.exec_command(cmd)
671 Log('contents of pts150gui below... \n\n' + WifiSearch)
672 else:
673 Log('adding in UseWifi=false')
674 cmd = r"sed -i '/\[wifi\]/,/\[wired\]/{ /^[[:space:]]*$/{ s//UseWifi=false\n/ } }' /etc/ptsenv/pts150gui.ini"
675 stdin, stdout, stderr = ssh.exec_command(cmd)
676 Log('contents of pts150gui below... \n\n' + WifiSearch)
677
678def WifiYes():
679 Log('Setting Wifi to True')
680 cmd = 'cat /etc/ptsenv/pts150gui.ini'
681 stdin, stdout, stderr = ssh.exec_command(cmd)
682 WifiSearch = stdout.read().strip().decode(encoding='utf-8')
683 Log('contents of pts150gui below... \n\n' + WifiSearch)
684 if 'UseWifi=true' in WifiSearch:
685 Log('WiFi already true')
686 PrintBox('WiFI already enabled')
687 elif 'UseWifi=false' in WifiSearch:
688 Log('changing UseWifi to true..')
689 cmd = "sed -i s/UseWifi=false/UseWifi=true/ /etc/ptsenv/pts150gui.ini"
690 stdin, stdout, stderr = ssh.exec_command(cmd)
691 Log('contents of pts150gui below... \n\n' + WifiSearch)
692 else:
693 Log('adding in UseWifi=true')
694 cmd = r"sed -i '/\[wifi\]/,/\[wired\]/{ /^[[:space:]]*$/{ s//UseWifi=true\n/ } }' /etc/ptsenv/pts150gui.ini"
695 stdin, stdout, stderr = ssh.exec_command(cmd)
696 Log('contents of pts150gui below... \n\n' + WifiSearch)
697
698def WifiCheck():
699 Clear()
700 global _WifiAnswer_
701 Log('Checking Wifi')
702 cmd = 'lsusb'
703 stdin, stdout, stderr = ssh.exec_command(cmd)
704 _wificheck = stdout.read().strip().decode(encoding='utf-8')
705 Log('contents of lsusb below... \n\n' + _wificheck)
706 ################ OLD CODE NOT NEEDED PER NEW CHECK METHOD ###########
707 #_WifiAnswer_ = input('Is this a WiFi unit?(Y/N): ')
708 #Log('user entered ' + _WifiAnswer_ + ' for ~is this wifi?~')
709 #_confirm_ = input('You entered ' + _WifiAnswer_ + ' are you sure? ')
710 #if _confirm_ == 'n':
711 # Log('user chose N on confirm, starting WiFiCheck over')
712 # WifiCheck()
713 ####################################################################
714 if 'Ralink' in _wificheck:
715 pass
716 else:
717 if _WifiAnswer_ == 'y':
718 Log('going to WifiYes()')
719 WifiYes()
720 else:
721 Log('going to WifiNo()')
722 WifiNo()
723
724def Upgrade():
725 CheckSSH()
726 WindsorBackup()
727 LocalClean()
728 PrintDirs()
729 RemoveFactory()
730 HomeFolder()
731 EnableTest()
732 RemoveCONFIGsav()
733# sftp.remove('/etc/ptsenv/CONFIG.sav')
734# PrintBox('removed CONFIG.sav')
735 time.sleep(5)
736 DisableTest()
737# ModeReplace()
738 EnableTest()
739 Log('Running Upgrade() ')
740 print('Checking update directory')
741 print(' Info on each file being worked on below..\n')
742 for filename in os.listdir(source):
743 print('____________________________\n')
744 print(' working on \n' + filename + '\n')
745 print(' moving.. \n' + os.path.join(source, filename) + '\n')
746 print('to.. \n' + os.path.join(destination, filename) + '\n')
747 print('(now doing actual command)')
748 Log('moving update files from pc to nexgen')
749 sftp.put(os.path.join(source, filename),
750 os.path.join(destination, filename))
751 print('____________________________\n')
752
753 print('changing dir to update folder..')
754 sftp.chdir('/tmp/updatesw')
755
756 #####################################
757 # #
758 # -Installing packages- #
759 # #
760 #####################################
761
762 PrintDirs()
763 for filename in sftp.listdir(destination):
764 filepath = os.path.join(destination, filename)
765 PrintBox('Installing ... ' + filepath)
766 logging.info('[' + time.strftime("%H:%M") + ']|> installing packages..')
767 cmd = 'ipkg install -force-overwrite -force-downgrade ' + filepath
768 stdin, stdout, stderr = ssh.exec_command(cmd)
769 Install = stdout.read().strip().decode(encoding='utf-8')
770 print(Install)
771 PrintBox('software installed..\n press any key to continue')
772 m.getch()
773 logging.info('[' + time.strftime("%H:%M") + ']|> sync after install')
774 stdin, stdout, stderr = ssh.exec_command('sync')
775 Sync = stdout.read().strip().decode(encoding='utf-8')
776 print(Sync)
777 DisableTest()
778 SDFix()
779 WifiCheck()
780 Reboot()
781
782
783def MountCheck():
784 CheckSSH()
785 PrintDirs()
786 Log('Running MountCheck() ')
787 cmd = 'mount | grep ptsenv'
788 #cmd = 'mount | grep i'
789 stdin, stdout, stderr = ssh.exec_command(cmd)
790 Mount = stdout.read().strip().decode(encoding='utf-8')
791 if Mount == '':
792 PrintBox(' Nothing mounted, moving to Install')
793 logging.info('[' + time.strftime("%H:%M") + ']|> nothing found, moving to install')
794 CheckUpdateSW()
795 else:
796 PrintBox('mount WAS NOT blank, doing copymount')
797 logging.info('[' + time.strftime("%H:%M") + ']|> mount found, going to CopyMount()')
798 #wait()
799 CopyMount()
800 MountCheck()
801 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
802
803 #####################################
804 # #
805 # _Files_ #
806 # Nexgen -> PC #
807 # #
808 #####################################
809def CopyMount():
810 HomeFolder()
811 os.chdir('temp')
812 sftp.chdir('/etc/')
813 path = 'ptsenv/'
814 Log('Running CopyMount()')
815 PrintDirs()
816 print('Backing up ptsenv folder...')
817 for filename in sftp.listdir('ptsenv'):
818 if 'root' not in filename:
819 if '~' not in filename:
820 if filename != 'default.cfg':
821 if filename != 'wpa_supplicant.d':
822 if filename != 'BATTERY.log':
823 if filename != 'mode.cfg':
824 print('filename is ' + filename)
825 filepath = os.path.join(path, filename)
826 print(' transferring... ' + filepath)
827 print('_______________________________________\n')
828 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
829 sftp.get(filepath, filepath)
830
831 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
832
833 sftp.chdir('ptsenv')
834 os.chdir('ptsenv')
835 path = 'wpa_supplicant.d/'
836 PrintDirs()
837 print('Backing up wpa_supplicant.d folder...')
838 for filename in sftp.listdir('wpa_supplicant.d'):
839 filepath = os.path.join(path, filename)
840 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
841 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
842 sftp.get(filepath, filepath)
843
844 PrintDirs()
845 HomeFolder()
846 os.chdir('temp')
847 sftp.chdir('/etc/')
848 path = 'unique/'
849 PrintDirs()
850 print('Backing up unique folder....')
851 for filename in sftp.listdir('unique'):
852 filepath = os.path.join(path, filename)
853 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
854 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
855 sftp.get(filepath, filepath)
856
857 sftp.chdir('/home/')
858 PrintDirs()
859 path = 'localdata/'
860 print('Backing up localdata folder....')
861 for filename in sftp.listdir('localdata'):
862 if 'PTS' in filename:
863 filepath = os.path.join(path, filename)
864 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
865 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
866 sftp.get(filepath, filepath)
867
868 print('Sync Before Unmount')
869 logging.info('[' + time.strftime("%H:%M") + ']|> sync before unmount')
870 stdin, stdout, stderr = ssh.exec_command('sync')
871 Sync = stdout.read().strip().decode(encoding='utf-8')
872 print(Sync)
873
874
875 #####################################
876 # #
877 # -unmountings- #
878 # #
879 #####################################
880
881 PrintDirs()
882 logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 5')
883 print('umounting mtdblock5\n')
884 cmd = 'umount /dev/mtdblock5'
885 stdin, stdout, stderr = ssh.exec_command(cmd)
886 Unmount5 = stdout.read().strip().decode(encoding='utf-8')
887 print(Unmount5)
888 print('MTDblock5 unmounted..\n')
889
890 logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 6')
891 print('umounting mtdblock6\n')
892 cmd = 'umount /dev/mtdblock6'
893 stdin, stdout, stderr = ssh.exec_command(cmd)
894 Unmount6 = stdout.read().strip().decode(encoding='utf-8')
895 print(Unmount6)
896 print('MTDblock6 unmounted...')
897
898 logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 7')
899 print('umounting mtdblock7\n')
900 cmd = 'umount /dev/mtdblock7'
901 stdin, stdout, stderr = ssh.exec_command(cmd)
902 Unmount7 = stdout.read().strip().decode(encoding='utf-8')
903 print(Unmount7)
904 print('MTDblock7 unmounted...')
905
906 logging.info('[' + time.strftime("%H:%M") + ']|> sync after unmount')
907 print('Sync after Unmount...')
908 stdin, stdout, stderr = ssh.exec_command('sync')
909 Sync = stdout.read().strip().decode(encoding='utf-8')
910 print(Sync)
911
912
913 #####################################
914 # #
915 # _Files_ #
916 # PC -> Nexgen #
917 # #
918 #####################################
919
920
921 sftp.chdir('/etc/')
922 path = 'ptsenv/'
923 PrintDirs()
924 print('deleting old ptsenv files from nexgen....')
925 for filename in sftp.listdir('ptsenv'):
926 if filename != 'wpa_supplicant.d':
927 filepath = os.path.join(path, filename)
928 PrintBox('filename is ' + filename + '\n removing... ' + filepath)
929 Log('Removing :' + filepath)
930 sftp.remove(filepath)
931 else:
932 print('no file')
933
934 print('restoring ptsenv files ....')
935 for filename in os.listdir('ptsenv'):
936 if filename != 'wpa_supplicant.d':
937 filepath = os.path.join(path, filename)
938 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
939 sftp.put(filepath, filepath)
940 else:
941 print('no file')
942
943 sftp.chdir('ptsenv')
944 os.chdir('ptsenv')
945 PrintDirs()
946 path = 'wpa_supplicant.d/'
947 try:
948 sftp.stat('wpa_supplicant.d')
949 except IOError as e:
950 if 'No such file' in str(e):
951 sftp.mkdir('wpa_supplicant.d')
952 else:
953 raise
954
955 print('deleting old wpa_supplicant.d files to nexgen....')
956 for filename in sftp.listdir('wpa_supplicant.d'):
957 filepath = os.path.join(path, filename)
958 PrintBox('filename is ' + filename + '\n removing... ' + filepath)
959 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
960 sftp.remove(filepath)
961 else:
962 print('no file')
963
964 print('restoring wpa_supplicant.d files ....')
965 PrintDirs()
966 for filename in os.listdir('wpa_supplicant.d'):
967 filepath = os.path.join(path, filename)
968 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
969 logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
970 sftp.put(filepath, filepath)
971 else:
972 print('no file')
973
974 os.chdir('..')
975 sftp.chdir('/etc/')
976 path = 'unique/'
977 PrintDirs()
978 print('deleting old unique files from nexgen....')
979 for filename in sftp.listdir('unique'):
980 filepath = os.path.join(path, filename)
981 PrintBox('filename is ' + filename + '\n removing... ' + filepath)
982 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
983 sftp.remove(filepath)
984 else:
985 print('no file')
986
987 print('restoring unique files ....')
988 for filename in os.listdir('unique'):
989 filepath = os.path.join(path, filename)
990 logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
991 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
992 sftp.put(filepath, filepath)
993 else:
994 print('no file')
995
996 sftp.chdir('/home/')
997 path = 'localdata/'
998 PrintDirs()
999 print('deleting old localdata files from nexgen....')
1000 for filename in sftp.listdir('localdata'):
1001 filepath = os.path.join(path, filename)
1002 PrintBox('filename is ' + filename + '\n removing... ' + filepath)
1003 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
1004 sftp.remove(filepath)
1005 else:
1006 print('no file')
1007
1008 print('restoring localdata files ....')
1009 for filename in os.listdir('localdata'):
1010 if 'PTS' in filename:
1011 filepath = os.path.join(path, filename)
1012 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1013 logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
1014 sftp.put(filepath,filepath)
1015 else:
1016 print('no file')
1017
1018 print('Last Sync')
1019 logging.info('[' + time.strftime("%H:%M") + ']|> final sync')
1020 stdin, stdout, stderr = ssh.exec_command('sync')
1021 Sync = stdout.read().strip().decode(encoding='utf-8')
1022 print(Sync)
1023
1024 print('finished copying files')
1025
1026 #####################################
1027 # #
1028 # _Cleanup_ #
1029 # #
1030 #####################################
1031def LocalClean():
1032 Clear()
1033 print('cleaning local files..')
1034 HomeFolder()
1035 os.chdir('temp')
1036 path = 'localdata/'
1037 print('removing localdata files from local computer...')
1038 for filename in os.listdir('localdata'):
1039 filepath = os.path.join(path, filename)
1040 print('Removing local file.. ' + filepath + '\n')
1041 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
1042 os.remove(filepath)
1043
1044 path = 'ptsenv/'
1045 print('removing ptsenv files from local computer...')
1046 for filename in os.listdir('ptsenv'):
1047 if filename != 'wpa_supplicant.d':
1048 filepath = os.path.join(path, filename)
1049 print('Removing local file.. ' + filepath + '\n')
1050 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
1051 os.remove(filepath)
1052
1053 path = 'unique/'
1054 print('removing unique files from local computer...')
1055 for filename in os.listdir('unique'):
1056 filepath = os.path.join(path, filename)
1057 print('Removing local file.. ' + filepath + '\n')
1058 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
1059 os.remove(filepath)
1060
1061 os.chdir('ptsenv')
1062 path = 'wpa_supplicant.d/'
1063 logging.info('removing wpa_supplicant.d files from local computer.....')
1064 print('removing wpa_supplicant.d files from local computer...')
1065 for filename in os.listdir('wpa_supplicant.d'):
1066 filepath = os.path.join(path, filename)
1067 print('Removing local file.. ' + filepath + '\n')
1068 print('Removing local file.. ' + filepath + '\n')
1069 logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
1070 os.remove(filepath)
1071 Clear()
1072
1073def EnableTest():
1074 CheckSSH()
1075 Clear()
1076 HomeFolder()
1077 Log('enabling test mode')
1078 Log('checking inittab file..')
1079 cmd = 'tail /etc/inittab'
1080 stdin, stdout, stderr = ssh.exec_command(cmd)
1081 AppSearch = stdout.read().strip().decode(encoding='utf-8')
1082 if '#zd' in AppSearch:
1083 PrintBox('Unit already in test mode\n\n press any key to continue')
1084 else:
1085 cmd = 'sed -i s/zd:/#zd:/ /etc/inittab'
1086 stdin, stdout, stderr = ssh.exec_command(cmd)
1087 stdin, stdout, stderr = ssh.exec_command('init q')
1088 PrintBox('Test mode is now ON \n\n press any key to continue')
1089 wait()
1090
1091def DisableTest():
1092 CheckSSH()
1093 Clear()
1094 HomeFolder()
1095 Log('disabling test mode')
1096 Log('checking inittab file..')
1097 cmd = 'tail /etc/inittab'
1098 stdin, stdout, stderr = ssh.exec_command(cmd)
1099 AppSearch = stdout.read().strip().decode(encoding='utf-8')
1100 if '#zd' in AppSearch:
1101 cmd = 'sed -i s/#zd:/zd:/ /etc/inittab'
1102 stdin, stdout, stderr = ssh.exec_command(cmd)
1103 else:
1104 PrintBox('unit was not in test mode.')
1105 #----------------------------------------------
1106 #-- 01.Dec.16 -
1107 # ---------------------------------------------
1108 # Adding in catch for test mode set in mode.cfg
1109 cmd = 'cat /etc/ptsenv/MODE.cfg'
1110 stdin, stdout, stderr = ssh.exec_command(cmd)
1111 AppSearch = stdout.read().strip().decode(encoding='utf-8')
1112 if '<entry key="TEST_MODE"><value>ON</value></entry>' in AppSearch:
1113 Log('Test Mode was enabled via MODE.cfg, disabling')
1114 cmd = "sed -i -e '/TEST_MODE/ s/ON/OFF/g' /etc/ptsenv/MODE.cfg"
1115 stdin, stdout, stderr = ssh.exec_command(cmd)
1116 if '<checksum>' in AppSearch:
1117 Log('checksum exists in MODE.cfg, removing')
1118 cmd = "sed -i -e '/checksum/d' /etc/ptsenv/MODE.cfg"
1119 stdin, stdout, stderr = ssh.exec_command(cmd)
1120 stdin, stdout, stderr = ssh.exec_command('init q')
1121 PrintBox('test mode disabled.')
1122 wait()
1123
1124def PuTTY():
1125 Clear()
1126 CheckSSH()
1127 Log('making sure unit is in test mode')
1128 cmd = 'tail /etc/inittab'
1129 stdin, stdout, stderr = ssh.exec_command(cmd)
1130 AppSearch = stdout.read().strip().decode(encoding='utf-8')
1131 if '#zd' in AppSearch:
1132 Log('unit already in test mode')
1133 PrintBox('Unit already in test mode')
1134 else:
1135 cmd = 'sed -i s/zd:/#zd:/ /etc/inittab'
1136 stdin, stdout, stderr = ssh.exec_command(cmd)
1137 stdin, stdout, stderr = ssh.exec_command('init q')
1138 Log('enabled test mode')
1139 PrintBox('Test mode is now ON')
1140 Clear()
1141 os.system('color 17')
1142 PrintBox('launching putty, utility will progress once window is closed \n\n' + \
1143 'Utility will disable test mode when putty is closed')
1144 winCMD = '.\putty.exe -ssh root@' + host + ' -pw ew3_llc'
1145 subprocess.call(winCMD)
1146 DisableTest()
1147 os.system('color 07')
1148
1149
1150def MapLDrive():
1151 # initialize
1152 logging.info('[' + time.strftime("%H:%M") + ']|> started MapLDrive')
1153 driveLetter = 'L:'
1154 networkPath = '\\\\10.45.4.254\Data\\nexgen-PTS\\logs'
1155 # logging.info('[' + time.strftime("%H:%M") + ']|> drive letter is ' +
1156 # driveLetter + '..')
1157 #logging.info('[' + time.strftime("%H:%M") + ']|> path is ' + networkPath +
1158 #'..')
1159
1160 # Disconnecting
1161 winCMD = 'NET USE ' + driveLetter + ' /delete /YES'
1162 logging.info('[' + time.strftime("%H:%M") + ']|> removing L: drive if it exists')
1163 #print(winCMD)
1164 subprocess.call(winCMD)
1165
1166 # Mapping
1167 winCMD = 'NET USE ' + driveLetter + ' ' + networkPath
1168 logging.info('[' + time.strftime("%H:%M") + ']|> mapping L drive')
1169 #print(winCMD)
1170 subprocess.call(winCMD)
1171 Clear()
1172
1173
1174def ClearWireless():
1175 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1176 logging.info('[' + time.strftime("%H:%M") + ']|> clearing wireless settings')
1177 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1178 Clear()
1179 print('Removing wireless profiles')
1180 RMfiles = ['wpa_supplicant.conf']
1181 Remove(RMfiles,'/etc/')
1182 RMfiles = ['pts150gui.ini']
1183 Remove(RMfiles,'/etc/ptsenv/')
1184 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1185
1186def ModeReplace():
1187 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1188 logging.info('[' + time.strftime("%H:%M") + ']|> entered ModeReplace()')
1189 Clear()
1190 try:
1191 sftp.stat('/etc/ptsenv/MODE.cfg')
1192 except IOError as e:
1193 if 'No such file' in str(e):
1194 print('no find found')
1195 sftp.put('MODE.cfg', '/etc/ptsenv/MODE.cfg')
1196 else:
1197 print('file found')
1198 sftp.remove('/etc/ptsenv/MODE.cfg')
1199 print('adding it back')
1200 sftp.put(UtilHome + '\MODE.cfg', '/etc/ptsenv/MODE.cfg')
1201 for filename in sftp.listdir('/etc/ptsenv/'):
1202 if filename == 'BATTERY.log':
1203 logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
1204 cmd = 'rm /etc/ptsenv/' + filename
1205 stdin, stdout, stderr = ssh.exec_command(cmd)
1206 _reboot = stdout.read().strip().decode(encoding='utf-8')
1207 stdin, stdout, stderr = ssh.exec_command('cmd')
1208 Clear()
1209
1210def RemoveConfig():
1211 Clear()
1212 HomeFolder()
1213 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1214 logging.info('[' + time.strftime("%H:%M") + ']|> running RemoveConfig().. ')
1215 RMfiles = ['SAMPLE_DB.cfg','LOT_CAL.cfg','PTSUSERS.cfg','DEFAULT.cfg']
1216 logging.info('[' + time.strftime("%H:%M") + ']|> RM files below... ')
1217 Remove(RMfiles,'/etc/ptsenv/')
1218
1219 logging.info('[' + time.strftime("%H:%M") + ']|> cleaning user / adding default admin... ')
1220 cmd = 'echo "admin;427c6d6148ce09e80004096df96dfe6a224dbcf3;2;1;2016-01-01;2099-01-01" > /etc/ptsenv/PTSUSERS.cfg'
1221 stdin, stdout, stderr = ssh.exec_command(cmd)
1222 logging.info('[' + time.strftime("%H:%M") + ']|> file added... ')
1223 logging.info('[' + time.strftime("%H:%M") + ']|> files currently in ptsenv ')
1224 PrintBox('Cleaning out ptsenv files..')
1225 PrintDirs()
1226 path = '/etc/ptsenv/'
1227 for filename in sftp.listdir('/etc/ptsenv/'):
1228 if 'root' in filename:
1229 print(' removing ' + filename)
1230 sftp.remove(path + filename)
1231 if '~' in filename:
1232 print(' removing ' + filename)
1233 sftp.remove(path + filename)
1234 if filename == 'default.cfg':
1235 print(' removing ' + filename)
1236 sftp.remove(path + filename)
1237 if filename == 'DEFAULT.cfg':
1238 print(' removing ' + filename)
1239 sftp.remove(path + filename)
1240 # if filename == 'wpa_supplicant.d':
1241 # os.remove(filename)
1242 if filename == 'BATTERY.log':
1243 print(' removing ' + filename)
1244 sftp.remove(path + filename)
1245# if filename == 'mode.cfg':
1246# print(' removing ' + filename)
1247# sftp.remove(path+filename)
1248# do not need to replace MODE.cfg
1249# ModeReplace()
1250 ClearWireless()
1251 Clear()
1252
1253def Copy2Remote():
1254 global SERIAL
1255 MapLDrive()
1256 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1257 logging.info('[' + time.strftime("%H:%M") + ']|> Entered Copy2Remote')
1258 os.chdir('L:\\')
1259 PrintDirs()
1260
1261 if os.path.exists(str(SERIAL)):
1262 logging.info('[' + time.strftime("%H:%M") + ']|> ' + str(SERIAL) + ' is there!')
1263 else:
1264 CreateOSFolder([str(SERIAL)])
1265 logging.info('[' + time.strftime("%H:%M") + ']|> created ' + str(SERIAL))
1266
1267 TimeStamp = time.strftime("%m_%d_%Y")
1268 Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
1269
1270 if os.path.exists(Ldrive):
1271 logging.info('[' + time.strftime("%H:%M") + ']|> ' + Ldrive + 'was not found, will use hour and minute')
1272 #Ldrive = str(SERIAL)+'\\' +
1273 #time.strftime("%Y-%m-%d_%H-%M")+'\Pre_Wipe'
1274 TimeStamp = time.strftime("%m_%d_%Y[%H-%M]")
1275 Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
1276 CreateOSFolder([Ldrive])
1277 logging.info('[' + time.strftime("%H:%M") + ']|> new Ldrive .. ' + Ldrive)
1278 else:
1279 logging.info('[' + time.strftime("%H:%M") + ']|>' + Ldrive + 'was not found, creating it')
1280 CreateOSFolder([Ldrive])
1281 logging.info('[' + time.strftime("%H:%M") + ']|> creating rest of folders for backup')
1282
1283 CreateOSFolder([Ldrive + '\Pre_Wipe',
1284 Ldrive + '\Pre_Wipe\etc', Ldrive + '\Pre_Wipe\etc\ptsenv', Ldrive + r'\Pre_Wipe\etc\unique',
1285 Ldrive + '\Pre_Wipe\\var', Ldrive + '\Pre_Wipe\\var\permalog',
1286 Ldrive + '\Pre_Wipe\home', Ldrive + '\Pre_Wipe\home\localdata'])
1287
1288 PrintBox('Utility will now begin transferring files\n from unit to network drive...')
1289 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1290 logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to : ' + Ldrive)
1291 logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
1292
1293 sftp.chdir('/etc/')
1294 os.chdir(Ldrive + '\Pre_Wipe\etc')
1295 path = 'ptsenv/'
1296 PrintDirs()
1297
1298 print('Backing up ptsenv folder...')
1299 for filename in sftp.listdir('ptsenv'):
1300 if filename == 'BATTERY.log':
1301 logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
1302 cmd = 'rm ' + filename
1303 stdin, stdout, stderr = ssh.exec_command(cmd)
1304 _reboot = stdout.read().strip().decode(encoding='utf-8')
1305 stdin, stdout, stderr = ssh.exec_command('cmd')
1306 elif filename != 'wpa_supplicant.d':
1307 if filename != 'BATTERY.log':
1308 filepath = os.path.join(path, filename)
1309 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1310 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1311 sftp.get(filepath, filepath)
1312
1313 path = 'unique/'
1314 PrintDirs()
1315 print('Backing up unique folder....')
1316 for filename in sftp.listdir('unique'):
1317 filepath = os.path.join(path, filename)
1318 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1319 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1320 sftp.get(filepath, filepath)
1321 os.chdir('..')
1322
1323 sftp.chdir('/home/')
1324 os.chdir('home')
1325 PrintDirs()
1326 path = 'localdata/'
1327 print('Backing up localdata folder....')
1328 for filename in sftp.listdir('localdata'):
1329 if 'PTS' in filename:
1330 filepath = os.path.join(path, filename)
1331 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1332 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1333 sftp.get(filepath, filepath)
1334 os.chdir('..')
1335
1336 sftp.chdir('/var/')
1337 os.chdir('var')
1338 path = 'permalog/'
1339 PrintDirs()
1340
1341 print('Backing up permalog folder....')
1342 for filename in sftp.listdir('permalog'):
1343 if filename == 'lost+found':
1344 print('Removing lost+found')
1345 logging.info('[' + time.strftime("%H:%M") + ']|> removing ' + path + 'lost+found')
1346 sftp.rmdir(path + 'lost+found')
1347 else:
1348 if filename != 'Templates':
1349 if filename != 'System Volume Information':
1350 filepath = os.path.join(path, filename)
1351 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1352 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1353 sftp.get(filepath, filepath)
1354
1355 os.chdir('..')
1356 PrintBox('Please clear reports from Nexgen device')
1357 wait()
1358 logging.info('[' + time.strftime("%H:%M") + ']|> finished pre wipe backup...')
1359 logging.info('[' + time.strftime("%H:%M") + ']|> removing files...')
1360
1361 RemoveConfig()
1362 for elem in sftp.listdir('/var/permalog/'):
1363 sftp.remove('/var/permalog/' + elem)
1364
1365 os.chdir('L:\\')
1366 logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to : ' + Ldrive)
1367 logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
1368 CreateOSFolder([Ldrive + '\Post_Wipe',
1369 Ldrive + '\Post_Wipe\etc', Ldrive + '\Post_Wipe\etc\ptsenv', Ldrive + r'\Post_Wipe\etc\unique',
1370 Ldrive + '\Post_Wipe\\var', Ldrive + '\Post_Wipe\\var\permalog',
1371 Ldrive + '\Post_Wipe\home', Ldrive + '\Post_Wipe\home\localdata'])
1372
1373 sftp.chdir('/etc/')
1374 os.chdir(Ldrive + '\Post_Wipe\etc')
1375 path = 'ptsenv/'
1376 PrintDirs()
1377 print('Backing up ptsenv folder...')
1378 for filename in sftp.listdir('ptsenv'):
1379 if filename == 'BATTERY.log':
1380 sftp.remove('BATTERY.log')
1381 elif filename != 'wpa_supplicant.d':
1382 filepath = os.path.join(path, filename)
1383 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1384 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1385 sftp.get(filepath, filepath)
1386
1387 path = 'unique/'
1388 PrintDirs()
1389 print('Backing up unique folder....')
1390 for filename in sftp.listdir('unique'):
1391 filepath = os.path.join(path, filename)
1392 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1393 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1394 sftp.get(filepath, filepath)
1395 os.chdir('..')
1396
1397 sftp.chdir('/home/')
1398 os.chdir('home')
1399 PrintDirs()
1400 path = 'localdata/'
1401 print('Backing up localdata folder....')
1402 for filename in sftp.listdir('localdata'):
1403 if 'PTS' in filename:
1404 filepath = os.path.join(path, filename)
1405 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1406 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1407 sftp.get(filepath, filepath)
1408 os.chdir('..')
1409
1410 sftp.chdir('/var/')
1411 os.chdir('var')
1412 path = 'permalog/'
1413 PrintDirs()
1414
1415 print('Backing up permalog folder....')
1416 for filename in sftp.listdir('permalog'):
1417 if filename != 'Templates':
1418 if filename != 'System Volume Information':
1419 filepath = os.path.join(path, filename)
1420 PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
1421 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
1422 sftp.get(filepath, filepath)
1423
1424 os.chdir('..')
1425 Clear()
1426 PrintBox('PTSenv & Permalog files backed up')
1427 HomeFolder()
1428 Reboot()
1429 Clear()
1430
1431
1432def ImageCapture():
1433 CheckSSH()
1434 HomeFolder()
1435 sftp.chdir('/usr/local/bin')
1436 Log('Running ImageCapture() ')
1437 PrintBox('Capturing screenshot, please wait..')
1438 try:
1439 sftp.stat('fbimage')
1440 except IOError as e:
1441 Log('file not found, transferring now')
1442 sftp.put('fbimage','/usr/local/bin/fbimage')
1443 else:
1444 print('')
1445 time.sleep(5)
1446 Log('setting permissions')
1447 cmd = "chmod 777 /usr/local/bin/fbimage"
1448 stdin, stdout, stderr = ssh.exec_command(cmd)
1449 setImage = stdout.read().strip().decode(encoding='utf-8')
1450 print(setImage)
1451 time.sleep(10)
1452 Log('taking screenshot')
1453 cmd = "/usr/local/bin/fbimage -d /dev/fb0 /usr/local/bin/image.png"
1454 stdin, stdout, stderr = ssh.exec_command(cmd)
1455 screenShot = stdout.read().strip().decode(encoding='utf-8')
1456 print(screenShot)
1457 PrintBox('Screenshot captured')
1458 Clear()
1459 HomeFolder()
1460 PrintBox('Transferring to computer..')
1461 screenCapture = './screenCaptures/' + SERIAL + '[' + time.strftime("%m_%d_%Y__%H-%M") + '].png'
1462 sftp.get('/usr/local/bin/image.png',screenCapture)
1463 time.sleep(5)
1464 im = Image.open(screenCapture)
1465 im.transpose(Image.ROTATE_90).save(screenCapture)
1466 sftp.remove('/usr/local/bin/image.png')
1467
1468def SendMail():
1469# FROM = "Nexgen-Utility@crl.com"
1470# TO = "Brandon.Dangerfield@crl.com"
1471 # Create message container - the correct MIME type is
1472 # multipart/alternative.
1473
1474 Log('Sending Mail....')
1475 s = smtplib.SMTP('smtp.cr.local')
1476
1477 msg = MIMEMultipart('alternative')
1478
1479 #email list
1480
1481
1482 msg['Subject'] = "Nexgen-PTS ERROR [SERIAL - %s]" % (SERIAL)
1483 msg['From'] = 'Nexgen-Utility@crl.com'
1484 msg['To'] = "brandon.dangerfield@crl.com, jason.tremblay@crl.com"
1485
1486 # Create the body of the message (a plain-text and an HTML version).
1487 text = """
1488 The system below has encountered an error
1489 The log file attached may not be up to date, please use ctrl+f to find the IP or SERIAL to find information on this unit.
1490
1491 System Information1
1492 Serial : %s
1493 IP Address : %s
1494 System Version: %s
1495 App Version: %s
1496 """ % (SERIAL,host,Version_System,Version_App)
1497 html = """\
1498 <html>
1499 <head></head>
1500 <body>
1501 The system below has encountered an error<br>
1502 The log file attached may not be up to date! <br><br>
1503 <table>
1504 <tr>
1505 <th colspan="2"><b><u><h1>System Information</h1></u></b></th>
1506 </tr>
1507 <tr>
1508 <td><b>Serial</b></td>
1509 <td>%s</td>
1510 </tr>
1511 <tr>
1512 <td><b>IP Address</b></td>
1513 <td>%s</td>
1514 </tr>
1515 <tr>
1516 <td><b>System Version</b></td>
1517 <td>%s</td>
1518 </tr>
1519 <tr>
1520 <td><b>App Version</b></td>
1521 <td>%s</td>
1522 </tr>
1523 </table>
1524 </body>
1525 </html>
1526 """ % (SERIAL,host,Version_System,Version_App)
1527 # Record the MIME types of both parts - text/plain and text/html.
1528 part1 = MIMEText(text, 'plain')
1529 part2 = MIMEText(html, 'html')
1530 part3 = MIMEApplication(open(Logname,"rb").read())
1531 part3.add_header('Content-Disposition', 'attachment', filename=Logname)
1532 # Attach parts into message container.
1533 # According to RFC 2046, the last part of a multipart message, in this case
1534 # the HTML message, is best and preferred.
1535 msg.attach(part1)
1536 msg.attach(part2)
1537 msg.attach(part3)
1538
1539 # sendmail function takes 3 arguments: sender's address, recipient's
1540 # address
1541 # and message to send - here it is sent as one string.
1542 s.sendmail(msg['From'],["brandon.dangerfield@crl.com", "jason.tremblay@crl.com"], msg.as_string())
1543 s.quit()
1544
1545def ResizeWindow():
1546 os.system('mode con: cols=90 lines=75')
1547
1548#s = smtplib.SMTP('smtp.uk.xensource.com')
1549#s.set_debuglevel(1)
1550#msg = MIMEText("""body""")
1551##sender = 'me@example.com'
1552#recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
1553#msg['Subject'] = "subject line"
1554#msg['From'] = sender
1555##msg['To'] = ", ".join(recipients)
1556#s.sendmail(sender, recipients, msg.as_string())
1557
1558
1559#################################
1560# #
1561# Options / ETC below #
1562# #
1563#################################
1564CreateOSFolder(['screenCaptures','logs','temp','temp/unique','temp/ptsenv','temp/ptsenv/wpa_supplicant.d','temp/localdata'])
1565
1566#Logging
1567Logname = './logs/Nexgen_Utility_Log_' + (time.strftime("%Y-%m-%d_%H-%M") + '.log')
1568logging.basicConfig(filename=Logname,level=logging.INFO)
1569logging = logging.getLogger(__name__)
1570
1571def main():
1572 Options()
1573
1574def Options():
1575 Clear()
1576# ResizeWindow()
1577 Log('Loading main...' + '\n' + ' ' + '\n' + ' Host : ' + host + '\n' + ' App Version :' + Version_App + '\n' + ' Serial Number : ' + SERIAL + '\n')
1578 print("""
1579______________________________________
1580| |
1581| Nexgen Update Utility |
1582| v 1.4 |
1583|_____________________________________|
1584
1585
1586
1587 Validated to install/upgrade
1588 version 10.2 and earlier releases
1589
1590 """)
1591
1592 print(' The current working directory...')
1593 print(' ' + os.getcwd())
1594
1595 PrintBox(' IP Address : ' + host + \
1596 '\nApplication version : ' + Version_App + \
1597# '\n System Version : '+ Version_System + \
1598 '\n Serial Number : ' + SERIAL)
1599 menu = {}
1600 print('Please choose one of the options below...\n')
1601 menu['[1]'] = "Set or Change IP Address"
1602 menu['[2]'] = "Get Set Point Value"
1603 menu['[3]'] = "Upgrade"
1604 menu['[4]'] = "Enable Test mode"
1605 menu['[5]'] = "Disable Test Mode"
1606 menu['[6]'] = "Backup files & Clean Unit \n______________________\n"
1607 menu['[7]'] = "Fix Config.sav"
1608 menu['[8]'] = "Take Screenshot \n______________________\n"
1609 menu['[9]'] = "Launch PuTTY \n______________________\n"
1610 #menu['[w]'] = "Set Wifi Model"
1611 menu['[x]'] = "Exit"
1612 while True:
1613 main = list(menu.keys())
1614 main.sort()
1615 for entry in main:
1616 print(entry, menu[entry])
1617 selection = input("\nPlease Select: ")
1618 if selection == "1":
1619 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [1]...')
1620 Clear()
1621 GetHost()
1622 Options()
1623 elif selection == '2':
1624 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [2]...')
1625 Clear()
1626 GetTemp()
1627 Options()
1628 elif selection == '3':
1629 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [3]...')
1630 Clear()
1631 #CheckUpdateSW()
1632 MountCheck()
1633 #Reboot()
1634 Options()
1635 elif selection == '4':
1636 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [4]...')
1637 Clear()
1638 EnableTest()
1639 CheckSD()
1640 Options()
1641 elif selection == '5':
1642 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [5]...')
1643 Clear()
1644 DisableTest()
1645 Options()
1646 elif selection == '6':
1647 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [6]...')
1648 CheckSSH()
1649 CheckSD()
1650 Copy2Remote()
1651 Options()
1652 elif selection == '7':
1653 Log('User selected [7]')
1654 Clear()
1655 EnableTest()
1656 sftp.remove('/etc/ptsenv/CONFIG.sav')
1657 Clear()
1658 DisableTest()
1659 Options()
1660 elif selection == '8':
1661 Log('User selected [8]')
1662 Clear()
1663 ImageCapture()
1664 Clear()
1665 Options()
1666 elif selection == '9':
1667 Log('User selected [9]')
1668 Clear()
1669 PuTTY()
1670 Options()
1671 elif selection == '77':
1672 Log('User selected [77]')
1673 SendMail()
1674 Options()
1675 #elif selection == 'w':
1676 # Log('User selected [w]')
1677 #WifiCheck()
1678 # Options()
1679 elif selection == 'x':
1680 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1681 logging.info('[' + time.strftime("%H:%M") + ']|> User selected [99]...')
1682 logging.info('[' + time.strftime("%H:%M") + ']|> CLOSING...')
1683 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1684 exit()
1685
1686 elif selection == 't':
1687 RemoveConfig()
1688 Options()
1689
1690 else:
1691 print("\nUnknown Option Selected!\n")
1692 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1693 logging.info('[' + time.strftime("%H:%M") + ']|> User input invalid selection...')
1694 logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
1695 wait()
1696 Clear()
1697 Options()
1698
1699#####################################
1700# #
1701# -Calling Functions- #
1702# #
1703#####################################
1704Clear()
1705if __name__ == Options():
1706 Options()