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