Advertisement
Guest User

Untitled

a guest
Feb 12th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 50.69 KB | None | 0 0
  1.  
  2. #
  3. #   Add later
  4. #  If value is blank when it goes to display it
  5. #   point out in log that the value is empty
  6. #####################
  7.  
  8. import errno
  9. import os
  10. import os.path
  11. import sys
  12. import cmd
  13. import paramiko
  14. import msvcrt as m
  15. import time
  16. import logging
  17. import subprocess
  18. import smtplib
  19. import sys
  20. from email.mime.multipart import MIMEMultipart
  21. from email.mime.text import MIMEText
  22. from email.mime.application import MIMEApplication
  23. from PIL import Image, ImageFilter
  24.  
  25. global username, password, port, host, SERIAL, Version_, _WorkDir_, source, destination, UtilHome
  26. password = "REMOVED"    #could prompt later
  27. username = "REMOVED"       #could prompt later
  28. port = 22
  29. host = ''
  30. Version_ = ''
  31. Version_App = ''
  32. Version_System = ''
  33. SERIAL = ''
  34. source = 'SoftwareUpgrade'
  35. destination = '/tmp/updatesw/'
  36. UtilHome = os.getcwd()
  37.  
  38. # Generic Log file line use
  39. # logging.info('[' + time.strftime("%H:%M") + ']|> ')
  40.  
  41. #####################################
  42. #                                   #
  43. #     -Defining Functions-          #
  44. #                                   #
  45. #####################################
  46.  
  47. def PrintBox(message):
  48.     print('\n__________________________________\n')
  49.     print(' ' + message)
  50.     print('\n__________________________________\n')
  51.  
  52. def Log(message):
  53.     logging.info(' _____________' + '[' + time.strftime("%H:%M") + ']___________')
  54.     logging.info(']|> ' + message)
  55.     logging.info(' ____________________________________________________________\n')
  56. #    logging.info('\n')
  57.  
  58. def FindType(TYPE):
  59.     Log(TYPE + ' is ' + type(TYPE))
  60.  
  61.  
  62. def CreateOSFolder(Folders):
  63.     for elem in Folders:
  64.         if not os.path.exists(elem):
  65.             logging.info('[' + time.strftime("%H:%M") + ']|> creating ' + elem)
  66.             os.mkdir(elem)
  67. def Clear():
  68.     Log('Running Clear()...')
  69.     os.system(['clear','cls'][os.name == 'nt'])
  70.  
  71. def wait():
  72.     Log('waiting...')
  73.     print('\n Press any key to continue..')
  74.     m.getch()
  75.     Clear()
  76.  
  77.  
  78. def HomeFolder():
  79.     # May go away with use of UtilHome
  80.     Log('moving to homefolder')
  81.     os.chdir(UtilHome)
  82.     Log('current Folder : ' + UtilHome)
  83.  
  84. def PrintDirs():
  85.     Log('Current OSdir - ' + os.getcwd() +
  86.         '\n Current SFTPdir ' + sftp.getcwd() + '\n Current UtilHome : ' + UtilHome)
  87. """
  88.    logging.info('[' + time.strftime("%H:%M") + ']|> printing current OS and SFTP drives...')
  89.    logging.info('[' + time.strftime("%H:%M") + '________________________________________')
  90.    logging.info('[' + time.strftime("%H:%M") + '________________________________________')
  91.    logging.info('[' + time.strftime("%H:%M") + ']|> Current OSdir - ' + os.getcwd() )
  92.    logging.info('[' + time.strftime("%H:%M") + ']|> Current SFTPdir  ' + sftp.getcwd())
  93.    logging.info('[' + time.strftime("%H:%M") + ']|> Current UtilHome  ' + UtilHome )
  94. """
  95.  
  96. def ClearHost():
  97.     global host, SERIAL, Version_App, Version_System
  98.     host = ''
  99.     SERIAL = ''
  100.     Version_App = ''
  101.     Version_System = ''
  102.     filepath = ''
  103.  
  104. def Reboot():
  105.     global host, SERIAL, Version_App, Version_System
  106.     Log('Rebooting..')
  107.     PrintBox('Please press any button\n   to reboot Nexgen')
  108.     cmd = 'reboot'
  109.     stdin, stdout, stderr = ssh.exec_command(cmd)
  110.     _reboot = stdout.read().strip().decode(encoding='utf-8')
  111.     stdin, stdout, stderr = ssh.exec_command('cmd')
  112.     ClearHost()
  113.     wait()
  114.     Clear()
  115.  
  116. def TestPing():
  117.     global host
  118.     print('contacting ' + host + ' ...')
  119.     Log('contacting ' +  host)
  120.     ping_result = subprocess.Popen(["ping.exe",host],stdout = subprocess.PIPE).communicate()[0]
  121.     if (b'unreachable' in ping_result):
  122.         Log('host unreachable')
  123.         print('\nHost unreachable, please try again')
  124.         wait()
  125.         GetHost()
  126.     elif (b'timed out.' in ping_result):
  127.         Log('host unreachable')
  128.         PrintBox('connection timed out, please try again')
  129.         wait()
  130.         Clear()
  131.         GetHost()
  132.     elif (b'failed' in ping_result):
  133.         Log('host unreachable')
  134.         PrintBox('ping failed, please try again')
  135.         wait()
  136.         Clear()
  137.         GetHost()
  138.     else:
  139.         Log('host online!')
  140.         PrintBox('host online')
  141.         ConnectSSH()
  142.  
  143. def GetHost():
  144.     HomeFolder()
  145.     global host
  146.     host = input('\nPlease Enter IP Address: ')
  147.     print('The IP Address has been changed to : ' + host + '\n')
  148.     Log('               > Entered GetHost() \n host : ' + host)
  149.     TestPing()
  150.     Clear()
  151.  
  152. def CheckSSH():
  153.     Clear()
  154.     Log('checking for host from CheckSSH')
  155.     if host == b'':
  156.         logging.info('no host found, asking for host IP')
  157.         print('*************************')
  158.         print('*  Need IP Address First*')
  159.         print('**************************')
  160.         GetHost()
  161.  
  162.  
  163. def CheckSD():
  164.     cmd = 'mount | grep ext2'
  165.     stdin, stdout, stderr = ssh.exec_command(cmd)
  166.     SDreults = stdout.read().strip().decode(encoding='utf-8')
  167.     if 'var/permalog' in SDreults:
  168.         Log('\n SD card check successful')
  169.         PrintBox('SD card check successful!')
  170.         wait()
  171.     else:
  172.         Log('\n SD card bad')
  173.         PrintBox('ISSUE WITH SD CARD\n    utility cannot continue')
  174.         SendMail()
  175.         wait()
  176.         exit()
  177.  
  178. def ConnectSSH():
  179.     Clear()
  180.     CheckSSH()
  181.     Log('Connecting to host...')
  182.     print('Connecting to ' + host)
  183.     global ssh, sftp
  184.     ssh = paramiko.SSHClient()
  185.     ssh.set_missing_host_key_policy(
  186.         paramiko.AutoAddPolicy())
  187.     ssh.connect( host, username = username, password = password)
  188.     print('    Connected to ' + host)
  189.     logging.info('connected to host ('+host+')')
  190.     sftp = ssh.open_sftp()
  191.     GetVersion()
  192.     GetSerial()
  193.  
  194.  
  195. def ChangeSerial():
  196.     Log('Changing Serial...')
  197.     sftp.chdir('/etc/unique/')
  198.     try:
  199.         sftp.stat('SERIAL')
  200.     except IOError as e:
  201.          print()
  202.     else:
  203.         sftp.remove('SERIAL')
  204.     HomeFolder()
  205.     os.chdir('temp/unique')
  206.     print('_______________________________________\n')
  207.     NewSerial = input('Please enter the correct/updated Serial number and press the enter key: \n\n'
  208.                           'New Serial: ')
  209.     f = open('SERIAL', 'w')
  210.     f.write(NewSerial)
  211.     f.close()
  212.     sftp.put('SERIAL','SERIAL')
  213.     LocalClean()
  214.     print('Serial Number updated, checking Serial Number on device..')
  215.     print('_______________________________________\n')
  216.     Log('serial set to '+ NewSerial)
  217.     ConnectSSH()
  218.  
  219. def SendCMD(cmd, VALUE):
  220.     print(' sending command.. ' + cmd)
  221.     stdin, stdout, stderr = ssh.exec_command(cmd)
  222.     VALUEcmd = stdout.read().strip().decode(encoding='utf-8')
  223.  
  224.  
  225.  
  226. def GetSerial():
  227.     global SERIAL
  228.     sftp.chdir('/etc/unique')
  229. #    SendCMD('head /etc/unique/SERIAL',SERIAL)
  230.     cmd = 'head /etc/unique/SERIAL'
  231.     stdin, stdout, stderr = ssh.exec_command(cmd)
  232.     SERIAL = stdout.read().strip().decode(encoding='utf-8')
  233.     Log('Current Serial: ' + SERIAL )
  234.     print('Please confirm that the serial number below \nmatches the label on the back of the device \n')
  235.     print("Serial: " + SERIAL + '\n')
  236.     _serialanswer_ =input('Is this serial correct?(Y/N) ')
  237.     if _serialanswer_ == b'N':
  238.         ChangeSerial()
  239.     elif _serialanswer_ == 'n':
  240.         ChangeSerial()
  241.     else:
  242.         print()
  243.  
  244. def GetVersion():
  245.     global Version_App, Version_System
  246.     cmd = "ipkg list_installed | grep pts150-application"
  247.     stdin, stdout, stderr = ssh.exec_command(cmd)
  248.     Version = stdout.read().strip().decode(encoding='utf-8')
  249.     Version_App = Version[Version.find("pts150-application - ")+20:Version.find(" - Application")]
  250.     global Version_
  251.     cmd = "ipkg list_installed | grep pts150-system"
  252.     stdin, stdout, stderr = ssh.exec_command(cmd)
  253.     Version = stdout.read().strip().decode(encoding='utf-8')
  254.     Version_System = Version[Version.find("pts150-system - ")+16:Version.find(" - System")]
  255.     #Version_System = bytes(Version_System, encoding='utf-8')
  256.     PrintBox('Application version is :' + Version_App)
  257.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  258.  
  259.  
  260. def GetTemp():
  261.     CheckSSH()
  262.     #ConnectSSH()
  263.     global Temp
  264. #    cmd = "grep -Eo 'C100ths</comment><value>[-1 -9]+' /etc/ptsenv/THERM.cfg"
  265.     cmd = "grep -Eo 'Calibration Temperature Offset C100ths</comment><value>-*[0-9]+' /etc/ptsenv/THERM.cfg"
  266.     stdin, stdout, stderr = ssh.exec_command(cmd)
  267.     Temp = stdout.read().strip().decode(encoding='utf-8')
  268.     TempValue = Temp[55:]
  269.     if TempValue == "":
  270.         print('no value found')
  271.         cmd = "head -10 /etc/ptsenv/THERM.cfg | tail -1 | grep value"
  272.         stdin, stdout, stderr = ssh.exec_command(cmd)
  273.         Temp = stdout.read().strip().decode(encoding='utf-8')
  274.         TempValue = Temp[7:]
  275.     else:
  276.         print ('')
  277.     PrintBox('The set point value is: ' + TempValue)
  278.     Log('Set Value is ' + TempValue)
  279.     wait()
  280.  
  281. def Remove(RMfiles,path):
  282.     CheckSSH()
  283.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  284.     logging.info('[' + time.strftime("%H:%M") + ']|> Running Remove(): ')
  285.     for elem in RMfiles:
  286.         print('\n___________________________')
  287.         print('Looking for ' + elem + ' .....')
  288.         if elem in sftp.listdir(path):
  289.             print('Removing ' + elem  + '....')
  290.             print('___________________________\n')
  291.             logging.info('[' + time.strftime("%H:%M") + ']|> removing following files :')
  292.             logging.info('[' + time.strftime("%H:%M") + ']|> ' + elem )
  293.             sftp.remove(path+elem)
  294.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  295.  
  296. def RemoveRemoteDir():
  297.     CheckSSH()
  298.     ConnectSSH()
  299.     PrintDirs()
  300.     Log('Running RemoveRemoteDir() ')
  301.     for filename in sftp.listdir(destination):
  302.         filepath = os.path.join(destination, filename)
  303.         print('removing ' + filename)
  304.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  305.         sftp.remove(filepath)
  306.     print('\n removing ' + destination)
  307.     logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + destination)
  308.     sftp.rmdir(destination)
  309.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  310.  
  311. def RemoveFactory():
  312.     CheckSSH()
  313.     Log('Running RemoveFactory()')
  314.     RMfiles = ['FACTORY']
  315.     Remove(RMfiles,'/etc/ptsenv/')
  316.  
  317.  
  318. def CheckUpdateSW():
  319.     CheckSSH()
  320.     Log('Running CheckUpdateSW() ')
  321.     print(' Checking for ('+ destination +')\n')
  322.     try:
  323.         sftp.stat(destination)
  324.     except IOError as e:
  325.          if 'No such file' in str(e):
  326.              print('update folder not found..')
  327.              print('creating updatesw directory')
  328.              logging.info('[' + time.strftime("%H:%M") + ']|> creating /tmp/updatesw')
  329.              sftp.mkdir('/tmp/updatesw')
  330.              print('proceeding to upgrade..')
  331.              Upgrade()
  332.     else:
  333.         print('Folder already exists..\n')
  334.         print('removing old folder')
  335.         RemoveRemoteDir()
  336.         print('folder removed\n')
  337.         print('removing host IP from utility..')
  338.         host = ''
  339.         print('(host value should be blank)')
  340.         print('host : ' + host)
  341.         print('going back to menu...')
  342.         PrintBox('unit already had update folder \nyou are about to return to menu \n please choose upgrade again')
  343.         Clear()
  344.         CheckUpdateSW()
  345.         logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  346.  
  347.  
  348. def WindsorBackup():
  349.     global SERIAL
  350.     MapLDrive()
  351.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  352.     logging.info('[' + time.strftime("%H:%M") + ']|> Entered WindsorBackup')
  353.     os.chdir('L:\\')
  354.     PrintDirs()
  355.  
  356.     if os.path.exists(str(SERIAL)):
  357.         logging.info('[' + time.strftime("%H:%M") + ']|> ' + str(SERIAL) + ' is there!' )
  358.     else:
  359.         CreateOSFolder([str(SERIAL)])
  360.         logging.info('[' + time.strftime("%H:%M") + ']|> created ' + str(SERIAL) )
  361.  
  362.     TimeStamp = time.strftime("%m_%d_%Y")
  363.     Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
  364.  
  365.     if os.path.exists(Ldrive):
  366.         logging.info('[' + time.strftime("%H:%M") + ']|> ' + Ldrive + 'was not found, will use hour and minute')
  367.         #Ldrive = str(SERIAL)+'\\' + time.strftime("%Y-%m-%d_%H-%M")+'\Pre_Wipe'
  368.         TimeStamp = time.strftime("%m_%d_%Y[%H-%M]")
  369.         Ldrive = 'L:\\' +  str(SERIAL)+'\\' + TimeStamp
  370.         CreateOSFolder([Ldrive])
  371.         logging.info('[' + time.strftime("%H:%M") + ']|> new Ldrive .. ' + Ldrive)
  372.     else:
  373.         logging.info('[' + time.strftime("%H:%M") + ']|>' + Ldrive +  'was not found, creating it')
  374.         CreateOSFolder([Ldrive])
  375.     logging.info('[' + time.strftime("%H:%M") + ']|> creating rest of folders for backup')
  376.  
  377.     CreateOSFolder([
  378.         Ldrive+'\Windsor_Backup',
  379.         Ldrive+'\Windsor_Backup\etc', Ldrive+'\Windsor_Backup\etc\ptsenv', Ldrive+r'\Windsor_Backup\etc\unique',
  380.         Ldrive+'\Windsor_Backup\\var', Ldrive+'\Windsor_Backup\\var\permalog',
  381.         Ldrive+'\Windsor_Backup\home', Ldrive+'\Windsor_Backup\home\localdata'])
  382.  
  383.     PrintBox('Utility will now begin transferring files\n from unit to network drive...')
  384.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  385.     logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to :  ' + Ldrive)
  386.     logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
  387.  
  388.     sftp.chdir('/etc/')
  389.     os.chdir(Ldrive+'\Windsor_Backup\etc')
  390.     path = 'ptsenv/'
  391.     PrintDirs()
  392.  
  393.     print('Backing up ptsenv folder...')
  394.     for filename in sftp.listdir('ptsenv'):
  395.         if filename == 'BATTERY.log':
  396.             logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
  397.             cmd = 'rm ' + filename
  398.             stdin, stdout, stderr = ssh.exec_command(cmd)
  399.         elif filename != 'wpa_supplicant.d':
  400.             if filename != 'BATTERY.log':
  401.                 filepath = os.path.join(path, filename)
  402.                 PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  403.                 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  404.                 sftp.get(filepath, filepath)
  405.  
  406.     path ='unique/'
  407.     PrintDirs()
  408.     print('Backing up unique folder....')
  409.     for filename in sftp.listdir('unique'):
  410.         filepath = os.path.join(path, filename)
  411.         PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  412.         logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  413.         sftp.get(filepath, filepath)
  414.     os.chdir('..')
  415.  
  416.     sftp.chdir('/home/')
  417.     os.chdir('home')
  418.     PrintDirs()
  419.     path = 'localdata/'
  420.     print('Backing up localdata folder....')
  421.     for filename in sftp.listdir('localdata'):
  422.         if 'PTS' in filename:
  423.             filepath = os.path.join(path, filename)
  424.             PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  425.             logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  426.             sftp.get(filepath, filepath)
  427.     os.chdir('..')
  428.  
  429.     sftp.chdir('/var/')
  430.     os.chdir('var')
  431.     path ='permalog/'
  432.     PrintDirs()
  433.  
  434.     print('Backing up permalog folder....')
  435.     for filename in sftp.listdir('permalog'):
  436.         if filename == 'lost+found':
  437.             print('Removing lost+found')
  438.             logging.info('[' + time.strftime("%H:%M") + ']|> removing ' + path + 'lost+found')
  439.             sftp.rmdir(path + 'lost+found')
  440.         else:
  441.             if filename != 'Templates':
  442.                 if filename != 'System Volume Information':
  443.                     filepath = os.path.join(path, filename)
  444.                     PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  445.                     logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  446.                     sftp.get(filepath, filepath)
  447.  
  448.     os.chdir('..')
  449.     wait()
  450.     logging.info('[' + time.strftime("%H:%M") + ']|> finished pre wipe backup...')
  451.     logging.info('[' + time.strftime("%H:%M") + ']|> removing files...')
  452.     Clear()
  453.  
  454.  
  455. def Upgrade():
  456.     CheckSSH()
  457.     WindsorBackup()
  458.     LocalClean()
  459.     PrintDirs()
  460.     RemoveFactory()
  461.     HomeFolder()
  462.     EnableTest()
  463.     sftp.remove('/etc/ptsenv/CONFIG.sav')
  464.     PrintBox('removed CONFIG.sav')
  465.     time.sleep(5)
  466.     DisableTest()
  467.     ModeReplace()
  468.     Log('Running Upgrade() ')
  469.     print('Checking update directory')
  470.     print(' Info on each file being worked on below..\n')
  471.     for filename in os.listdir(source):
  472.         print('____________________________\n')
  473.         print(' working on \n' +  filename + '\n')
  474.         print('  moving.. \n' +  os.path.join(source, filename)+ '\n')
  475.         print('to.. \n' + os.path.join(destination, filename) + '\n')
  476.         print('(now doing actual command)')
  477.         logging.info('[' + time.strftime("%H:%M") + ']|> moving update files from pc to nexgen')
  478.         sftp.put(
  479.             os.path.join(source, filename),
  480.             os.path.join(destination, filename) )
  481.     print('____________________________\n')
  482.  
  483.     print('changing dir to update folder..')
  484.     sftp.chdir('/tmp/updatesw')
  485.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  486.  
  487.  
  488.              #####################################
  489.             #                                   #
  490.             #     -Installing packages-         #
  491.             #                                   #
  492.             #####################################
  493.  
  494.     PrintDirs()
  495.     for filename in sftp.listdir(destination):
  496.         filepath = os.path.join(destination, filename)
  497.         PrintBox('Installing ... \n' +  filepath)
  498.         logging.info('[' + time.strftime("%H:%M") + ']|> installing packages..')
  499.         cmd = 'ipkg install -force-overwrite ' + filepath
  500.         stdin, stdout, stderr = ssh.exec_command(cmd)
  501.         Install = stdout.read().strip().decode(encoding='utf-8')
  502.         print(Install)
  503.         print('Package installed')
  504.     logging.info('[' + time.strftime("%H:%M") + ']|> sync after install')
  505.     stdin, stdout, stderr = ssh.exec_command('sync')
  506.     Sync = stdout.read().strip().decode(encoding='utf-8')
  507.     print(Sync)
  508.     PrintBox('Install Complete')
  509.     Log('Install Complete. ')
  510.     wait()
  511.     Reboot()
  512.  
  513.  
  514. def MountCheck():
  515.     CheckSSH()
  516.     PrintDirs()
  517.     Log('Running MountCheck() ')
  518.     cmd = 'mount | grep ptsenv'
  519.     #cmd = 'mount | grep i'
  520.     stdin, stdout, stderr = ssh.exec_command(cmd)
  521.     Mount = stdout.read().strip().decode(encoding='utf-8')
  522.     if Mount == '':
  523.         PrintBox('   Nothing mounted, moving to Install')
  524.         logging.info('[' + time.strftime("%H:%M") + ']|> nothing found, moving to install')
  525.         CheckUpdateSW()
  526.     else:
  527.         PrintBox('mount WAS NOT blank, doing copymount')
  528.         logging.info('[' + time.strftime("%H:%M") + ']|> mount found, going to CopyMount()')
  529.         #wait()
  530.         CopyMount()
  531.         MountCheck()
  532.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  533.  
  534.                     #####################################
  535.                     #                                   #
  536.                     #            _Files_                #
  537.                     #          Nexgen -> PC             #
  538.                     #                                   #
  539.                     #####################################
  540. def CopyMount():
  541.     HomeFolder()
  542.     os.chdir('temp')
  543.     sftp.chdir('/etc/')
  544.     path = 'ptsenv/'
  545.     Log('Running CopyMount()')
  546.     PrintDirs()
  547.     print('Backing up ptsenv folder...')
  548.     for filename in sftp.listdir('ptsenv'):
  549.         if 'root' not in filename:
  550.             if '~' not in filename:
  551.                 if filename != 'default.cfg':
  552.                     if filename != 'wpa_supplicant.d':
  553.                         if filename != 'BATTERY.log':
  554.                             if filename != 'mode.cfg':
  555.                                 print('filename is ' + filename)
  556.                                 filepath = os.path.join(path, filename)
  557.                                 print(' transferring... ' + filepath)
  558.                                 print('_______________________________________\n')
  559.                                 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  560.                                 sftp.get(filepath, filepath)
  561.  
  562.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  563.  
  564.     sftp.chdir('ptsenv')
  565.     os.chdir('ptsenv')
  566.     path = 'wpa_supplicant.d/'
  567.     PrintDirs()
  568.     print('Backing up wpa_supplicant.d folder...')
  569.     for filename in sftp.listdir('wpa_supplicant.d'):
  570.         filepath = os.path.join(path, filename)
  571.         PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  572.         logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  573.         sftp.get(filepath, filepath)
  574.  
  575.     PrintDirs()
  576.     HomeFolder()
  577.     os.chdir('temp')
  578.     sftp.chdir('/etc/')
  579.     path ='unique/'
  580.     PrintDirs()
  581.     print('Backing up unique folder....')
  582.     for filename in sftp.listdir('unique'):
  583.         filepath = os.path.join(path, filename)
  584.         PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  585.         logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  586.         sftp.get(filepath, filepath)
  587.  
  588.     sftp.chdir('/home/')
  589.     PrintDirs()
  590.     path = 'localdata/'
  591.     print('Backing up localdata folder....')
  592.     for filename in sftp.listdir('localdata'):
  593.         if 'PTS' in filename:
  594.             filepath = os.path.join(path, filename)
  595.             PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  596.             logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  597.             sftp.get(filepath, filepath)
  598.  
  599.     print('Sync Before Unmount')
  600.     logging.info('[' + time.strftime("%H:%M") + ']|> sync before unmount')
  601.     stdin, stdout, stderr = ssh.exec_command('sync')
  602.     Sync = stdout.read().strip().decode(encoding='utf-8')
  603.     print(Sync)
  604.  
  605.  
  606.                 #####################################
  607.                 #                                   #
  608.                 #         -unmountings-             #
  609.                 #                                   #
  610.                 #####################################
  611.  
  612.     PrintDirs()
  613.     logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 5')
  614.     print('umounting mtdblock5\n')
  615.     cmd = 'umount /dev/mtdblock5'
  616.     stdin, stdout, stderr = ssh.exec_command(cmd)
  617.     Unmount5 = stdout.read().strip().decode(encoding='utf-8')
  618.     print(Unmount5)
  619.     print('MTDblock5 unmounted..\n')
  620.  
  621.     logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 6')
  622.     print('umounting mtdblock6\n')
  623.     cmd = 'umount /dev/mtdblock6'
  624.     stdin, stdout, stderr = ssh.exec_command(cmd)
  625.     Unmount6 = stdout.read().strip().decode(encoding='utf-8')
  626.     print(Unmount6)
  627.     print('MTDblock6 unmounted...')
  628.  
  629.     logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 7')
  630.     print('umounting mtdblock7\n')
  631.     cmd = 'umount /dev/mtdblock7'
  632.     stdin, stdout, stderr = ssh.exec_command(cmd)
  633.     Unmount7 = stdout.read().strip().decode(encoding='utf-8')
  634.     print(Unmount7)
  635.     print('MTDblock7 unmounted...')
  636.  
  637.     logging.info('[' + time.strftime("%H:%M") + ']|> sync after unmount')
  638.     print('Sync after Unmount...')
  639.     stdin, stdout, stderr = ssh.exec_command('sync')
  640.     Sync = stdout.read().strip().decode(encoding='utf-8')
  641.     print(Sync)
  642.  
  643.  
  644.                     #####################################
  645.                     #                                   #
  646.                     #            _Files_                #
  647.                     #            PC -> Nexgen           #
  648.                     #                                   #
  649.                     #####################################
  650.  
  651.  
  652.     sftp.chdir('/etc/')
  653.     path = 'ptsenv/'
  654.     PrintDirs()
  655.     print('deleting old ptsenv files from nexgen....')
  656.     for filename in sftp.listdir('ptsenv'):
  657.         if filename != 'wpa_supplicant.d':
  658.             filepath = os.path.join(path, filename)
  659.             PrintBox('filename is ' + filename + '\n removing... ' + filepath)
  660.             Log('Removing :' + filepath)
  661.             sftp.remove(filepath)
  662.         else:
  663.             print('no file')
  664.  
  665.     print('restoring ptsenv files ....')
  666.     for filename in os.listdir('ptsenv'):
  667.         if filename != 'wpa_supplicant.d':
  668.             filepath = os.path.join(path, filename)
  669.             PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  670.             sftp.put(filepath, filepath)
  671.         else:
  672.             print('no file')
  673.  
  674.     sftp.chdir('ptsenv')
  675.     os.chdir('ptsenv')
  676.     PrintDirs()
  677.     path = 'wpa_supplicant.d/'
  678.     try:
  679.         sftp.stat('wpa_supplicant.d')
  680.     except IOError as e:
  681.          if 'No such file' in str(e):
  682.              sftp.mkdir('wpa_supplicant.d')
  683.     else:
  684.         raise
  685.  
  686.     print('deleting old wpa_supplicant.d files to nexgen....')
  687.     for filename in sftp.listdir('wpa_supplicant.d'):
  688.         filepath = os.path.join(path, filename)
  689.         PrintBox('filename is ' + filename + '\n removing... ' + filepath)
  690.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  691.         sftp.remove(filepath)
  692.     else:
  693.         print('no file')
  694.  
  695.     print('restoring wpa_supplicant.d files ....')
  696.     PrintDirs()
  697.     for filename in os.listdir('wpa_supplicant.d'):
  698.         filepath = os.path.join(path, filename)
  699.         PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  700.         logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
  701.         sftp.put(filepath, filepath)
  702.     else:
  703.         print('no file')
  704.  
  705.     os.chdir('..')
  706.     sftp.chdir('/etc/')
  707.     path ='unique/'
  708.     PrintDirs()
  709.     print('deleting old unique files from nexgen....')
  710.     for filename in sftp.listdir('unique'):
  711.         filepath = os.path.join(path, filename)
  712.         PrintBox('filename is ' + filename + '\n removing... ' + filepath)
  713.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  714.         sftp.remove(filepath)
  715.     else:
  716.         print('no file')
  717.  
  718.     print('restoring unique files ....')
  719.     for filename in os.listdir('unique'):
  720.         filepath = os.path.join(path, filename)
  721.         logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
  722.         PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  723.         sftp.put(filepath, filepath)
  724.     else:
  725.         print('no file')
  726.  
  727.     sftp.chdir('/home/')
  728.     path = 'localdata/'
  729.     PrintDirs()
  730.     print('deleting old localdata files from nexgen....')
  731.     for filename in sftp.listdir('localdata'):
  732.         filepath = os.path.join(path, filename)
  733.         PrintBox('filename is ' + filename + '\n removing... ' + filepath)
  734.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  735.         sftp.remove(filepath)
  736.     else:
  737.         print('no file')
  738.  
  739.     print('restoring localdata files ....')
  740.     for filename in os.listdir('localdata'):
  741.         if 'PTS' in filename:
  742.             filepath = os.path.join(path, filename)
  743.             PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
  744.             logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
  745.             sftp.put(filepath,filepath)
  746.         else:
  747.             print('no file')
  748.  
  749.     print('Last Sync')
  750.     logging.info('[' + time.strftime("%H:%M") + ']|> final sync')
  751.     stdin, stdout, stderr = ssh.exec_command('sync')
  752.     Sync = stdout.read().strip().decode(encoding='utf-8')
  753.     print(Sync)
  754.  
  755.     print('finished copying files')
  756.  
  757.                     #####################################
  758.                     #                                   #
  759.                     #          _Cleanup_                #
  760.                     #                                   #
  761.                     #####################################
  762.  
  763. def LocalClean():
  764.     Clear()
  765.     print('cleaning local files..')
  766.     HomeFolder()
  767.     os.chdir('temp')
  768.     path = 'localdata/'
  769.     print('removing localdata files from local computer...')
  770.     for filename in os.listdir('localdata'):
  771.         filepath = os.path.join(path, filename)
  772.         print('Removing local file.. ' + filepath + '\n')
  773.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  774.         os.remove(filepath)
  775.  
  776.     path = 'ptsenv/'
  777.     print('removing ptsenv files from local computer...')
  778.     for filename in os.listdir('ptsenv'):
  779.          if filename != 'wpa_supplicant.d':
  780.              filepath = os.path.join(path, filename)
  781.              print('Removing local file.. ' + filepath + '\n')
  782.              logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  783.              os.remove(filepath)
  784.  
  785.     path ='unique/'
  786.     print('removing unique files from local computer...')
  787.     for filename in os.listdir('unique'):
  788.         filepath = os.path.join(path, filename)
  789.         print('Removing local file.. ' + filepath + '\n')
  790.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  791.         os.remove(filepath)
  792.  
  793.     os.chdir('ptsenv')
  794.     path = 'wpa_supplicant.d/'
  795.     logging.info('removing wpa_supplicant.d files from local computer.....')
  796.     print('removing wpa_supplicant.d files from local computer...')
  797.     for filename in os.listdir('wpa_supplicant.d'):
  798.         filepath = os.path.join(path, filename)
  799.         print('Removing local file.. ' + filepath + '\n')
  800.         logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
  801.         os.remove(filepath)
  802.     Clear()
  803.  
  804.  
  805. def EnableTest():
  806.     CheckSSH()
  807.     Clear()
  808.     HomeFolder()
  809.     logging.info('[' + time.strftime("%H:%M") + ']|> enabling test mode')
  810.     print('Enabling test mode....')
  811.     source = 'inittab_noapp'
  812.     destination = '/etc/inittab'
  813.     t = paramiko.Transport((host, port))
  814.     t.connect(username = username, password = password)
  815.     sftp = paramiko.SFTPClient.from_transport(t)
  816.     sftp.remove('/etc/inittab')
  817.     sftp.put('inittab_noapp','/etc/inittab')
  818.     cmd = "init q"
  819.     stdin, stdout, stderr = ssh.exec_command('init q')
  820.     print("Test mode is now ON")
  821.     wait()
  822.  
  823. def DisableTest():
  824.     CheckSSH()
  825.     Clear()
  826.     HomeFolder()
  827.     logging.info('[' + time.strftime("%H:%M") + ']|> disabling test mode')
  828.     print('Disabling test mode....')
  829.     source = 'inittab_app'
  830.     destination = '/etc/inittab'
  831.     t = paramiko.Transport((host, port))
  832.     t.connect(username = username, password = password)
  833.     sftp = paramiko.SFTPClient.from_transport(t)
  834.     sftp.remove('/etc/inittab')
  835.     sftp.put('inittab_app','/etc/inittab')
  836.     stdin, stdout, stderr = ssh.exec_command('init q')
  837.     print("Test mode is now OFF")
  838.     wait()
  839.  
  840.  
  841. def MapLDrive():
  842.     # initialize
  843.     logging.info('[' + time.strftime("%H:%M") + ']|> started MapLDrive')
  844.     driveLetter = 'L:'
  845.     networkPath = '\\\\10.45.4.254\Data\\nexgen-PTS\\logs'
  846.    # logging.info('[' + time.strftime("%H:%M") + ']|> drive letter is ' + driveLetter + '..')
  847.     #logging.info('[' + time.strftime("%H:%M") + ']|> path is ' + networkPath + '..')
  848.  
  849.     # Disconnecting
  850.     winCMD = 'NET USE ' + driveLetter + ' /delete /YES'
  851.     logging.info('[' + time.strftime("%H:%M") + ']|> removing L: drive if it exists')
  852.     #print(winCMD)
  853.     subprocess.call(winCMD)
  854.  
  855.     # Mapping
  856.     winCMD = 'NET USE ' + driveLetter + ' ' + networkPath
  857.     logging.info('[' + time.strftime("%H:%M") + ']|> mapping L drive')
  858.     #print(winCMD)
  859.     subprocess.call(winCMD)
  860.     Clear()
  861.  
  862.  
  863. def ClearWireless():
  864.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  865.     logging.info('[' + time.strftime("%H:%M") + ']|> clearing wireless settings')
  866.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  867.     Clear()
  868.     print('Removing wireless profiles')
  869.     RMfiles = ['wpa_supplicant.conf']
  870.     Remove(RMfiles,'/etc/')
  871.     RMfiles = ['pts150gui.ini']
  872.     Remove(RMfiles,'/etc/ptsenv/')
  873.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  874.  
  875. def ModeReplace():
  876.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  877.     logging.info('[' + time.strftime("%H:%M") + ']|>  entered ModeReplace()')
  878.     Clear()
  879.     try:
  880.         sftp.stat('/etc/ptsenv/MODE.cfg')
  881.     except IOError as e:
  882.         if 'No such file' in str(e):
  883.             print('no find found')
  884.             sftp.put('MODE.cfg', '/etc/ptsenv/MODE.cfg')
  885.     else:
  886.         print('file found')
  887.         sftp.remove('/etc/ptsenv/MODE.cfg')
  888.         print('adding it back')
  889.         sftp.put(UtilHome + '\MODE.cfg', '/etc/ptsenv/MODE.cfg')
  890.     for filename in sftp.listdir('/etc/ptsenv/'):
  891.         if filename == 'BATTERY.log':
  892.             logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
  893.             cmd = 'rm /etc/ptsenv/' + filename
  894.             stdin, stdout, stderr = ssh.exec_command(cmd)
  895.             _reboot = stdout.read().strip().decode(encoding='utf-8')
  896.             stdin, stdout, stderr = ssh.exec_command('cmd')
  897.     Clear()
  898.  
  899. def RemoveConfig():
  900.     Clear()
  901.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  902.     logging.info('[' + time.strftime("%H:%M") + ']|> running RemoveConfig().. ')
  903.     RMfiles = ['SAMPLE_DB.cfg','LOT_CAL.cfg','PTSUSERS.cfg','DEFAULT.cfg']
  904.     logging.info('[' + time.strftime("%H:%M") + ']|> RM files below... ')
  905.     Remove(RMfiles,'/etc/ptsenv/')
  906.     logging.info('[' + time.strftime("%H:%M") + ']|> files currently in ptsenv ')
  907.     print('Cleaning out ptsenv files..')
  908.     PrintDirs()
  909.     path = '/etc/ptsenv/'
  910.     for filename in sftp.listdir('/etc/ptsenv/'):
  911.         if 'root' in filename:
  912.             print(' removing ' + filename)
  913.             sftp.remove(path+filename)
  914.         if '~' in filename:
  915.             print(' removing ' + filename)
  916.             sftp.remove(path+filename)
  917.         if filename == 'default.cfg':
  918.             print(' removing ' + filename)
  919.             sftp.remove(path+filename)
  920.         if filename == 'DEFAULT.cfg':
  921.             print(' removing ' + filename)
  922.             sftp.remove(path+filename)
  923.     #    if filename == 'wpa_supplicant.d':
  924.     #        os.remove(filename)
  925.         if filename == 'BATTERY.log':
  926.             print(' removing ' + filename)
  927.             sftp.remove(path+filename)
  928.         if filename == 'mode.cfg':
  929.             print(' removing ' + filename)
  930.             sftp.remove(path+filename)
  931.     ModeReplace()
  932.     ClearWireless()
  933.     Clear()
  934.  
  935. def Copy2Remote():
  936.     global SERIAL
  937.     MapLDrive()
  938.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  939.     logging.info('[' + time.strftime("%H:%M") + ']|> Entered Copy2Remote')
  940.     os.chdir('L:\\')
  941.     PrintDirs()
  942.  
  943.     if os.path.exists(str(SERIAL)):
  944.         logging.info('[' + time.strftime("%H:%M") + ']|> ' + str(SERIAL) + ' is there!' )
  945.     else:
  946.         CreateOSFolder([str(SERIAL)])
  947.         logging.info('[' + time.strftime("%H:%M") + ']|> created ' + str(SERIAL) )
  948.  
  949.     TimeStamp = time.strftime("%m_%d_%Y")
  950.     Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
  951.  
  952.     if os.path.exists(Ldrive):
  953.         logging.info('[' + time.strftime("%H:%M") + ']|> ' + Ldrive + 'was not found, will use hour and minute')
  954.         #Ldrive = str(SERIAL)+'\\' + time.strftime("%Y-%m-%d_%H-%M")+'\Pre_Wipe'
  955.         TimeStamp = time.strftime("%m_%d_%Y[%H-%M]")
  956.         Ldrive = 'L:\\' +  str(SERIAL)+'\\' + TimeStamp
  957.         CreateOSFolder([Ldrive])
  958.         logging.info('[' + time.strftime("%H:%M") + ']|> new Ldrive .. ' + Ldrive)
  959.     else:
  960.         logging.info('[' + time.strftime("%H:%M") + ']|>' + Ldrive +  'was not found, creating it')
  961.         CreateOSFolder([Ldrive])
  962.     logging.info('[' + time.strftime("%H:%M") + ']|> creating rest of folders for backup')
  963.  
  964.     CreateOSFolder([
  965.         Ldrive+'\Pre_Wipe',
  966.         Ldrive+'\Pre_Wipe\etc', Ldrive+'\Pre_Wipe\etc\ptsenv', Ldrive+r'\Pre_Wipe\etc\unique',
  967.         Ldrive+'\Pre_Wipe\\var', Ldrive+'\Pre_Wipe\\var\permalog',
  968.         Ldrive+'\Pre_Wipe\home', Ldrive+'\Pre_Wipe\home\localdata'])
  969.  
  970.     PrintBox('Utility will now begin transferring files\n from unit to network drive...')
  971.     logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  972.     logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to :  ' + Ldrive)
  973.     logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
  974.  
  975.     sftp.chdir('/etc/')
  976.     os.chdir(Ldrive+'\Pre_Wipe\etc')
  977.     path = 'ptsenv/'
  978.     PrintDirs()
  979.  
  980.     print('Backing up ptsenv folder...')
  981.     for filename in sftp.listdir('ptsenv'):
  982.         if filename == 'BATTERY.log':
  983.             logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
  984.             cmd = 'rm ' + filename
  985.             stdin, stdout, stderr = ssh.exec_command(cmd)
  986.             _reboot = stdout.read().strip().decode(encoding='utf-8')
  987.             stdin, stdout, stderr = ssh.exec_command('cmd')
  988.         elif filename != 'wpa_supplicant.d':
  989.             if filename != 'BATTERY.log':
  990.                 filepath = os.path.join(path, filename)
  991.                 PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  992.                 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  993.                 sftp.get(filepath, filepath)
  994.  
  995.     path ='unique/'
  996.     PrintDirs()
  997.     print('Backing up unique folder....')
  998.     for filename in sftp.listdir('unique'):
  999.         filepath = os.path.join(path, filename)
  1000.         PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1001.         logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1002.         sftp.get(filepath, filepath)
  1003.     os.chdir('..')
  1004.  
  1005.     sftp.chdir('/home/')
  1006.     os.chdir('home')
  1007.     PrintDirs()
  1008.     path = 'localdata/'
  1009.     print('Backing up localdata folder....')
  1010.     for filename in sftp.listdir('localdata'):
  1011.         if 'PTS' in filename:
  1012.             filepath = os.path.join(path, filename)
  1013.             PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1014.             logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1015.             sftp.get(filepath, filepath)
  1016.     os.chdir('..')
  1017.  
  1018.     sftp.chdir('/var/')
  1019.     os.chdir('var')
  1020.     path ='permalog/'
  1021.     PrintDirs()
  1022.  
  1023.     print('Backing up permalog folder....')
  1024.     for filename in sftp.listdir('permalog'):
  1025.         if filename == 'lost+found':
  1026.             print('Removing lost+found')
  1027.             logging.info('[' + time.strftime("%H:%M") + ']|> removing ' + path + 'lost+found')
  1028.             sftp.rmdir(path + 'lost+found')
  1029.         else:
  1030.             if filename != 'Templates':
  1031.                 if filename != 'System Volume Information':
  1032.                     filepath = os.path.join(path, filename)
  1033.                     PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1034.                     logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1035.                     sftp.get(filepath, filepath)
  1036.  
  1037.     os.chdir('..')
  1038.     PrintBox('Please clear reports from Nexgen device')
  1039.     wait()
  1040.     logging.info('[' + time.strftime("%H:%M") + ']|> finished pre wipe backup...')
  1041.     logging.info('[' + time.strftime("%H:%M") + ']|> removing files...')
  1042.  
  1043.     RemoveConfig()
  1044.     for elem in sftp.listdir('/var/permalog/'):
  1045.         sftp.remove('/var/permalog/'+elem)
  1046.  
  1047.     os.chdir('L:\\')
  1048.     logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to :  ' + Ldrive)
  1049.     logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
  1050.     CreateOSFolder([
  1051.         Ldrive+'\Post_Wipe',
  1052.         Ldrive+'\Post_Wipe\etc', Ldrive+'\Post_Wipe\etc\ptsenv', Ldrive+r'\Post_Wipe\etc\unique',
  1053.         Ldrive+'\Post_Wipe\\var', Ldrive+'\Post_Wipe\\var\permalog',
  1054.         Ldrive+'\Post_Wipe\home', Ldrive+'\Post_Wipe\home\localdata'
  1055.         ])
  1056.  
  1057.     sftp.chdir('/etc/')
  1058.     os.chdir(Ldrive+'\Post_Wipe\etc')
  1059.     path = 'ptsenv/'
  1060.     PrintDirs()
  1061.     print('Backing up ptsenv folder...')
  1062.     for filename in sftp.listdir('ptsenv'):
  1063.         if filename == 'BATTERY.log':
  1064.             sftp.remove('BATTERY.log')
  1065.         elif filename != 'wpa_supplicant.d':
  1066.             filepath = os.path.join(path, filename)
  1067.             PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1068.             logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1069.             sftp.get(filepath, filepath)
  1070.  
  1071.     path ='unique/'
  1072.     PrintDirs()
  1073.     print('Backing up unique folder....')
  1074.     for filename in sftp.listdir('unique'):
  1075.         filepath = os.path.join(path, filename)
  1076.         PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1077.         logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1078.         sftp.get(filepath, filepath)
  1079.     os.chdir('..')
  1080.  
  1081.     sftp.chdir('/home/')
  1082.     os.chdir('home')
  1083.     PrintDirs()
  1084.     path = 'localdata/'
  1085.     print('Backing up localdata folder....')
  1086.     for filename in sftp.listdir('localdata'):
  1087.         if 'PTS' in filename:
  1088.             filepath = os.path.join(path, filename)
  1089.             PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1090.             logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1091.             sftp.get(filepath, filepath)
  1092.     os.chdir('..')
  1093.  
  1094.     sftp.chdir('/var/')
  1095.     os.chdir('var')
  1096.     path ='permalog/'
  1097.     PrintDirs()
  1098.  
  1099.     print('Backing up permalog folder....')
  1100.     for filename in sftp.listdir('permalog'):
  1101.         if filename != 'Templates':
  1102.             if filename != 'System Volume Information':
  1103.                 filepath = os.path.join(path, filename)
  1104.                 PrintBox('filename is ' + filename + '\n  transferring... ' + filepath)
  1105.                 logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
  1106.                 sftp.get(filepath, filepath)
  1107.  
  1108.     os.chdir('..')
  1109.     Clear()
  1110.     PrintBox('PTSenv & Permalog files backed up')
  1111.     HomeFolder()
  1112.     Reboot()
  1113.     Clear()
  1114.  
  1115.  
  1116. def ImageCapture():
  1117.     CheckSSH()
  1118.     HomeFolder()
  1119.     sftp.chdir('/usr/local/bin')
  1120.     Log('Running ImageCapture() ')
  1121.     PrintBox('Capturing screenshot, please wait..')
  1122.     try:
  1123.         sftp.stat('fbimage')
  1124.     except IOError as e:
  1125.         Log('file not found, transferring now')
  1126.         sftp.put('fbimage','/usr/local/bin/fbimage')
  1127.     else:
  1128.         print('')
  1129.     time.sleep(5)
  1130.     Log('setting permissions')
  1131.     cmd = "chmod 777 /usr/local/bin/fbimage"
  1132.     stdin, stdout, stderr = ssh.exec_command(cmd)
  1133.     setImage = stdout.read().strip().decode(encoding='utf-8')
  1134.     print(setImage)
  1135.     time.sleep(10)
  1136.     Log('taking screenshot')
  1137.     cmd = "/usr/local/bin/fbimage -d /dev/fb0 /usr/local/bin/image.png"
  1138.     stdin, stdout, stderr = ssh.exec_command(cmd)
  1139.     screenShot = stdout.read().strip().decode(encoding='utf-8')
  1140.     print(screenShot)
  1141.     PrintBox('Screenshot captured')
  1142.     Clear()
  1143.     HomeFolder()
  1144.     PrintBox('Transferring to computer..')
  1145.     screenCapture = './screenCaptures/'+ SERIAL + '[' + time.strftime("%m_%d_%Y__%H-%M") + '].png'
  1146.     sftp.get('/usr/local/bin/image.png',screenCapture)
  1147.     time.sleep(5)
  1148.     im = Image.open(screenCapture)
  1149.     im.transpose(Image.ROTATE_90).save(screenCapture)
  1150.     sftp.remove('/usr/local/bin/image.png')
  1151.  
  1152. def SendMail():
  1153. #    FROM = "Nexgen-Utility@crl.com"
  1154. #    TO = "Brandon.Dangerfield@crl.com"
  1155.     # Create message container - the correct MIME type is multipart/alternative.
  1156.  
  1157.     Log('Sending Mail....')
  1158.     s = smtplib.SMTP('smtp.cr.local')
  1159.  
  1160.     msg = MIMEMultipart('alternative')
  1161.  
  1162.     #email list
  1163.  
  1164.  
  1165.     msg['Subject'] = "Nexgen-PTS ERROR [SERIAL - %s]"%(SERIAL)
  1166.     msg['From'] = 'Nexgen-Utility@crl.com'
  1167.     msg['To'] = "Jason.Tremblay@crl.com"
  1168.  
  1169.     # Create the body of the message (a plain-text and an HTML version).
  1170.     text = """
  1171.            The system below has encountered an error
  1172.            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.
  1173.  
  1174.                    System Information1
  1175.                    Serial :        %s
  1176.                    IP Address :    %s
  1177.                    System Version: %s
  1178.                    App Version:    %s
  1179.        """ %(SERIAL,host,Version_System,Version_App)
  1180.     html = """\
  1181.    <html>
  1182.      <head></head>
  1183.      <body>
  1184.        The system below has encountered an error<br>
  1185.        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.<br><br>
  1186.            <table>
  1187.              <tr>
  1188.                <th colspan="2"><b><u><h1>System Information</h1></u></b></th>
  1189.              </tr>
  1190.              <tr>
  1191.                <td><b>Serial</b></td>
  1192.                <td>%s</td>
  1193.              </tr>
  1194.              <tr>
  1195.                <td><b>IP Address</b></td>
  1196.                <td>%s</td>
  1197.              </tr>
  1198.              <tr>
  1199.                <td><b>System Version</b></td>
  1200.                <td>%s</td>
  1201.              </tr>
  1202.              <tr>
  1203.                <td><b>App Version</b></td>
  1204.                <td>%s</td>
  1205.              </tr>
  1206.            </table>
  1207.      </body>
  1208.    </html>
  1209.    """%(SERIAL,host,Version_System,Version_App)
  1210.     # Record the MIME types of both parts - text/plain and text/html.
  1211.     part1 = MIMEText(text, 'plain')
  1212.     part2 = MIMEText(html, 'html')
  1213.     part3 = MIMEApplication(open(Logname,"rb").read())
  1214.     part3.add_header('Content-Disposition', 'attachment', filename=Logname)
  1215.     # Attach parts into message container.
  1216.     # According to RFC 2046, the last part of a multipart message, in this case
  1217.     # the HTML message, is best and preferred.
  1218.     msg.attach(part1)
  1219.     msg.attach(part2)
  1220.     msg.attach(part3)
  1221.  
  1222.     # sendmail function takes 3 arguments: sender's address, recipient's address
  1223.     # and message to send - here it is sent as one string.
  1224.     s.sendmail(msg['From'],recipients, msg.as_string())
  1225.     s.quit()
  1226.  
  1227. #################################
  1228. #                               #
  1229. #    Options / ETC below        #
  1230. #                               #
  1231. #################################
  1232. CreateOSFolder(['screenCaptures','logs','temp','temp/unique','temp/ptsenv','temp/ptsenv/wpa_supplicant.d','temp/localdata'])
  1233.  
  1234. #Logging
  1235. Logname='./logs/Nexgen_Utility_Log_'+(time.strftime("%Y-%m-%d_%H-%M")+'.log')
  1236. logging.basicConfig(filename=Logname,level=logging.DEBUG)
  1237. logging = logging.getLogger(__name__)
  1238.  
  1239. def main():
  1240.     Options()
  1241.  
  1242. def Options():
  1243.     Log('Loading main...' + '\n' +
  1244.         '                  ' + '\n' +
  1245.         '                  Host          : ' + host + '\n'+
  1246.         '                  App Version   :' + Version_App + '\n'+
  1247.         '                  Serial Number : ' + SERIAL + '\n')
  1248.     print("""
  1249. ______________________________________
  1250. |                                     |
  1251. |       Nexgen Update Utility         |
  1252. |                v1.1.7               |
  1253. |_____________________________________|
  1254.    """)
  1255.  
  1256.     print('    The current working directory...')
  1257.     print('  ' + os.getcwd())
  1258.  
  1259.     PrintBox('        IP Address :  ' + host + \
  1260.              '\nApplication version : ' + Version_App + \
  1261. #             '\n     System Version :  '+ Version_System + \
  1262.              '\n      Serial Number :  ' + SERIAL
  1263.              )
  1264.     menu = {}
  1265.     print('Please choose one of the options below...\n')
  1266.     menu['[1]']="Set or Change IP Address"
  1267.     menu['[2]']="Get Set Point Value"
  1268.     menu['[3]']="Upgrade"
  1269.     menu['[4]']="Enable Test mode"
  1270.     menu['[5]']="Disable Test Mode"
  1271.     menu['[6]']="Backup files & Clean Unit \n______________________\n"
  1272.     menu['[7]']="Fix Config.sav"
  1273.     menu['[8]']="Take Screenshot \n______________________\n"
  1274. #    menu['[9]']="Mode Replace \n______________________\n"
  1275.     menu['[99]']="Exit"
  1276.     while True:
  1277.         main=list(menu.keys())
  1278.         main.sort()
  1279.         for entry in main:
  1280.             print(entry, menu[entry])
  1281.         selection=input("\nPlease Select: ")
  1282.         if selection =="1":
  1283.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [1]...')
  1284.             Clear()
  1285.             GetHost()
  1286.             Options()
  1287.         elif selection == '2':
  1288.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [2]...')
  1289.             Clear()
  1290.             GetTemp()
  1291.             Options()
  1292.         elif selection == '3':
  1293.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [3]...')
  1294.             Clear()
  1295.             #CheckUpdateSW()
  1296.             MountCheck()
  1297.             #Reboot()
  1298.             Options()
  1299.         elif selection == '4':
  1300.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [4]...')
  1301.             Clear()
  1302.             EnableTest()
  1303.             CheckSD()
  1304.             Options()
  1305.         elif selection == '5':
  1306.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [5]...')
  1307.             Clear()
  1308.             DisableTest()
  1309.             Options()
  1310.         elif selection == '6':
  1311.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [6]...')
  1312.             CheckSSH()
  1313.             CheckSD()
  1314.             Copy2Remote()
  1315.             Options()
  1316.         elif selection == '7':
  1317.             Log('User selected [7]')
  1318.             Clear()
  1319.             EnableTest()
  1320.             sftp.remove('/etc/ptsenv/CONFIG.sav')
  1321.             Clear()
  1322.             DisableTest()
  1323.             Options()
  1324.         elif selection == '8':
  1325.             Log('User selected [8]')
  1326.             Clear()
  1327.             ImageCapture()
  1328.             Clear()
  1329.             Options()
  1330.         elif selection == '77':
  1331.             Log('User selected [77]')
  1332.             SendMail()
  1333.             Options()
  1334.         elif selection == '99':
  1335.             logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  1336.             logging.info('[' + time.strftime("%H:%M") + ']|> User selected [99]...')
  1337.             logging.info('[' + time.strftime("%H:%M") + ']|> CLOSING...')
  1338.             logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  1339.             exit()
  1340.  
  1341.         else:
  1342.             print("\nUnknown Option Selected!\n")
  1343.             logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  1344.             logging.info('[' + time.strftime("%H:%M") + ']|> User  input invalid selection...')
  1345.             logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
  1346.             wait()
  1347.             Clear()
  1348.             Options()
  1349.  
  1350. #####################################
  1351. #                                   #
  1352. #     -Calling Functions-           #
  1353. #                                   #
  1354. #####################################
  1355. Clear()
  1356. if __name__ == Options():
  1357.     Options()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement