Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Test Ip's below #
- #
- # 10.45.4.141
- # 10.45.4.192
- # 10.45.4.93
- #####################
- #
- # Add later
- # If value is blank when it goes to display it
- # point out in log that the value is empty
- #####################
- import errno
- import os
- import os.path
- import sys
- import cmd
- import paramiko
- import msvcrt as m
- import time
- import logging
- import subprocess
- import smtplib
- import sys
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- from email.mime.application import MIMEApplication
- from PIL import Image, ImageFilter
- global username, password, port, host, SERIAL, Version_, _WorkDir_, source, destination, UtilHome
- password = "ew3_llc" #could prompt later
- username = "root" #could prompt later
- port = 22
- host = ''
- Version_ = ''
- Version_App = ''
- Version_System = ''
- SERIAL = ''
- source = 'SoftwareUpgrade'
- destination = '/tmp/updatesw/'
- UtilHome = os.getcwd()
- cmdOUTPUT = ""
- # Generic Log file line use
- # logging.info('[' + time.strftime("%H:%M") + ']|> ')
- #####################################
- # #
- # -Defining Functions- #
- # #
- #####################################
- def PrintBox(message):
- print('\n__________________________________\n')
- print(' ' + message)
- print('\n__________________________________\n')
- def Log(message):
- logging.info(' _____________[' + time.strftime("%H:%M") + ']___________')
- logging.info(']|> ' + message)
- logging.info(' ____________________________________________________________\n')
- # logging.info('\n')
- def FindType(TYPE):
- Log(TYPE + ' is ' + type(TYPE))
- def CreateOSFolder(Folders):
- for elem in Folders:
- if not os.path.exists(elem):
- logging.info('[' + time.strftime("%H:%M") + ']|> creating ' + elem)
- os.mkdir(elem)
- def Clear():
- Log('Running Clear()...')
- os.system(['clear','cls'][os.name == 'nt'])
- def wait():
- Log('waiting...')
- print('\n Press any key to continue..')
- m.getch()
- Clear()
- def HomeFolder():
- # May go away with use of UtilHome
- Log('moving to homefolder')
- os.chdir(UtilHome)
- Log('current Folder : ' + UtilHome)
- def PrintDirs():
- Log('Current OSdir - ' + os.getcwd() + '\n Current SFTPdir ' + sftp.getcwd() + '\n Current UtilHome : ' + UtilHome)
- def ClearHost():
- Log('cleaning host information..')
- global host, SERIAL, Version_App, Version_System
- host = ''
- SERIAL = ''
- Version_App = ''
- Version_System = ''
- filepath = ''
- def Reboot():
- global host, SERIAL, Version_App, Version_System
- Log('Rebooting..')
- PrintBox('Please press any button\n to reboot Nexgen')
- m.getch()
- cmd = 'reboot'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- _reboot = stdout.read().strip().decode(encoding='utf-8')
- stdin, stdout, stderr = ssh.exec_command('cmd')
- ClearHost()
- Clear()
- def TestPing():
- Log('entered test ping()....')
- global host
- print('contacting ' + host + ' ...')
- Log('contacting ' + host)
- ping_result = subprocess.Popen(["ping.exe",host],stdout = subprocess.PIPE).communicate()[0]
- if (b'unreachable' in ping_result):
- Log('host unreachable')
- print('\nHost unreachable, please try again')
- wait()
- GetHost()
- elif (b'timed out.' in ping_result):
- Log('host unreachable')
- PrintBox('connection timed out, please try again')
- wait()
- Clear()
- GetHost()
- elif (b'failed' in ping_result):
- Log('host unreachable')
- PrintBox('ping failed, please try again')
- wait()
- Clear()
- GetHost()
- else:
- Log('host online!')
- PrintBox('host online')
- ConnectSSH()
- def GetHost():
- HomeFolder()
- global host
- host = input('\nPlease Enter IP Address: ')
- print('The IP Address has been changed to : ' + host + '\n')
- Log(' > Entered GetHost() \n host : ' + host)
- TestPing()
- WifiCheck()
- Clear()
- def CheckSSH():
- Clear()
- Log('checking for host from CheckSSH')
- if host == '':
- logging.info('no host found, asking for host IP')
- PrintBox('Need IP Address First!')
- GetHost()
- def KillAll():
- Log('entered KillAll()...')
- CheckSSH()
- Clear()
- PrintBox('Working on SD card....')
- Log('Starting Format_SD ..')
- cmd = 'tail /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- AppSearch = stdout.read().strip().decode(encoding='utf-8')
- Log('inittab info below... \n\n' + AppSearch + '\n')
- if '#za' in AppSearch:
- Log('#za already commented out')
- else:
- Log('commenting za out')
- cmd = 'sed -i s/za:/#za:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- try:
- time.sleep(5)
- finally:
- print('')
- if '#zb' in AppSearch:
- Log('#zb already commented out')
- else:
- Log('commenting zb out')
- cmd = 'sed -i s/zb:/#zb:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- time.sleep(5)
- if '#zc' in AppSearch:
- Log('#zc already commented out')
- else:
- Log('commenting zc out')
- cmd = 'sed -i s/zc:/#zc:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- try:
- time.sleep(5)
- finally:
- print('')
- if '#zd' in AppSearch:
- Log('#z already commented out')
- else:
- Log('commenting zd out')
- cmd = 'sed -i s/zd:/#zd:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- try:
- time.sleep(5)
- finally:
- print('')
- stdin, stdout, stderr = ssh.exec_command('init q')
- time.sleep(5)
- Log('stopping mclient ..')
- stdin, stdout, stderr = ssh.exec_command('sh /etc/init.d/mclientd stop')
- try:
- time.sleep(5)
- finally:
- print('')
- Log('stopping syslog ..')
- stdin, stdout, stderr = ssh.exec_command('sh /etc/init.d/syslog stop')
- try:
- time.sleep(5)
- finally:
- print('')
- cmd = 'mount'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- MOUNTlog = stdout.read().strip().decode(encoding='utf-8')
- Log('Mount info BEFORE unmount below... \n\n' + MOUNTlog + '\n')
- def ReviveAll():
- Log('running sed, then will output contents of file')
- print('changing from vfat -> auto...')
- cmd = 'sed -i s/vfat/auto/ /etc/fstab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- time.sleep(4)
- cmd = 'cat /etc/fstab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- FSTABlog = stdout.read().strip().decode(encoding='utf-8')
- Log('FSTAB BELOW>..\n\n: ' + FSTABlog + '\n')
- PrintBox('restoring inittab file..')
- cmd = 'tail /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- AppSearch = stdout.read().strip().decode(encoding='utf-8')
- #will make function/array in future iteration
- if '#za' in AppSearch:
- Log('un-commenting za out')
- cmd = 'sed -i s/#za:/za:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- else:
- Log('za not commented out')
- time.sleep(5)
- if '#zb' in AppSearch:
- Log('un-commenting zb out')
- cmd = 'sed -i s/#zb:/zb:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- else:
- Log('zb not commented out')
- time.sleep(5)
- if '#zc' in AppSearch:
- Log('un-commenting zc out')
- cmd = 'sed -i s/#zc:/zc:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- else:
- Log('zc not commented out')
- time.sleep(5)
- if '#zd' in AppSearch:
- Log('un-commenting zd out')
- cmd = 'sed -i s/#zd:/zd:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- else:
- Log('zd not commented out')
- time.sleep(5)
- cmd = 'mount'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- MOUNTlog = stdout.read().strip().decode(encoding='utf-8')
- Log('Mount info BEFORE unmount below... \n\n' + MOUNTlog + '\n')
- def Fdisk():
- KillAll()
- Log('Starting Format_SD ..\n running fdisk ..')
- cmd = '(echo d; echo n; echo p; echo 1; echo ; echo ; echo w;) | fdisk /dev/mmcblk0'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- def MKFS():
- Clear()
- Log('Starting Format_SD ..\n umounting ..')
- print('making filesystem, takes about 85 seconds...')
- cmd = 'mkfs.ext3 /dev/mmcblk0p1'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- time.sleep(85)
- ReviveAll()
- def CheckSD():
- Log('entered CheckSD().....')
- cmd = "mount | grep '/dev/mmcblk0p1'"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- SDreults = stdout.read().strip().decode(encoding='utf-8')
- if 'var/permalog' in SDreults:
- Log('\n SD card check successful')
- PrintBox('SD card check successful!')
- wait()
- else:
- Log('\n SD card bad')
- PrintBox('App Version is... ' + Version_App + '\n press any key to continue\n')
- m.getch()
- if '10.0.6' in Version_App:
- Log('running mkfs command..')
- PrintBox('SD Card bad, fixing!\n\n Making filesystem...\n')
- Fdisk()
- MKFS()
- PrintBox('SD card repaired, preparing to reboot')
- time.sleep(10)
- Reboot()
- else:
- #PrintBox('unit not upgraded to 10.0.6, continuing')
- time.sleep(5)
- def SDFix():
- Log('entered SDFix()...')
- KillAll()
- cmd = 'umount -l /dev/mmcblk0p1'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- time.sleep(5)
- logging.info('[' + time.strftime("%H:%M") + ']|> running mkfs...')
- print('making filesystem...\n This will take about 85 seconds.. \n')
- cmd = 'mkfs.ext3 /dev/mmcblk0p1'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- time.sleep(85)
- cmd = 'mount /dev/mmcblk0p1'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- time.sleep(5)
- ReviveAll()
- def ConnectSSH():
- Clear()
- CheckSSH()
- Log('Connecting to host...')
- print('Connecting to ' + host)
- global ssh, sftp
- ssh = paramiko.SSHClient()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh.connect(host, username = username, password = password)
- print(' Connected to ' + host)
- logging.info('connected to host (' + host + ')')
- sftp = ssh.open_sftp()
- GetVersion()
- GetSerial()
- def ChangeSerial():
- Log('Changing Serial...')
- sftp.chdir('/etc/unique/')
- try:
- sftp.stat('SERIAL')
- except IOError as e:
- print()
- else:
- sftp.remove('SERIAL')
- HomeFolder()
- os.chdir('temp/unique')
- print('_______________________________________\n')
- NewSerial = input('Please enter the correct/updated Serial number and press the enter key: \n\n'
- 'New Serial: ')
- f = open('SERIAL', 'w')
- f.write(NewSerial)
- f.close()
- sftp.put('SERIAL','SERIAL')
- LocalClean()
- print('Serial Number updated, checking Serial Number on device..')
- print('_______________________________________\n')
- Log('serial set to ' + NewSerial)
- ConnectSSH()
- def SendCMD(cmd):
- global cmdOUTPUT
- Log('sending command.. ' + cmd)
- stdin, stdout, stderr = ssh.exec_command(cmd)
- cmdOUTPUT = stdout.read().strip().decode(encoding='utf-8')
- Log('output of ' + cmd + 'is below.. \n' + cmdOUTPUT)
- #print('output of ' + cmd + 'is below.. \n' + cmdOUTPUT)
- #wait()
- return cmdOUTPUT
- def GetSerial():
- global SERIAL
- sftp.chdir('/etc/unique')
- SERIAL = SendCMD('head /etc/unique/SERIAL')
- Log('Current Serial: ' + SERIAL)
- print('Please confirm that the serial number below \nmatches the label on the back of the device \n')
- print("Serial: " + SERIAL + '\n')
- _serialanswer_ = input('Is this serial correct?(Y/N) ')
- if _serialanswer_ == b'N':
- Log('user specified serial is incorrect')
- ChangeSerial()
- elif _serialanswer_ == 'n':
- Log('user specified serial is incorrect')
- ChangeSerial()
- else:
- Log('user specified serial is correct')
- print()
- def GetVersion():
- global Version_App, Version_System
- SendCMD("ipkg list_installed | grep pts150-application")
- Version = cmdOUTPUT
- Version_App = Version[Version.find("pts150-application - ") + 20:Version.find(" - Application")]
- global Version_
- SendCMD("ipkg list_installed | grep pts150-system")
- Version = cmdOUTPUT
- Version_System = Version[Version.find("pts150-system - ") + 16:Version.find(" - System")]
- PrintBox('Application version is :' + Version_App)
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- def GetTemp():
- CheckSSH()
- global Temp
- SendCMD("grep -Eo 'Calibration Temperature Offset C100ths</comment><value>-*[0-9]+' /etc/ptsenv/THERM.cfg")
- Temp = cmdOUTPUT
- TempValue = Temp[55:]
- if TempValue == "":
- print('no value found')
- SendCMD("head -10 /etc/ptsenv/THERM.cfg | tail -1 | grep value")
- Temp = cmdOUTPUT
- TempValue = Temp[7:]
- if '</value>' in TempValue:
- Log('removing </value> from TempValue')
- TempValue = TempValue.replace('</value>','')
- else:
- print('')
- else:
- print('')
- PrintBox('The set point value is: ' + TempValue)
- Log('Set Value is ' + TempValue)
- wait()
- def Remove(RMfiles,path):
- CheckSSH()
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> Running Remove(): ')
- for elem in RMfiles:
- print('\n___________________________')
- print('Looking for ' + elem + ' .....')
- if elem in sftp.listdir(path):
- print('Removing ' + elem + '....')
- print('___________________________\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing following files :')
- logging.info('[' + time.strftime("%H:%M") + ']|> ' + elem)
- sftp.remove(path + elem)
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- def RemoveRemoteDir():
- CheckSSH()
- ConnectSSH()
- PrintDirs()
- Log('Running RemoveRemoteDir() ')
- for filename in sftp.listdir(destination):
- filepath = os.path.join(destination, filename)
- print('removing ' + filename)
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- sftp.remove(filepath)
- print('\n removing ' + destination)
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + destination)
- sftp.rmdir(destination)
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- def RemoveFactory():
- CheckSSH()
- Log('Running RemoveFactory()')
- RMfiles = ['FACTORY']
- Remove(RMfiles,'/etc/ptsenv/')
- def RemoveCONFIGsav():
- CheckSSH()
- Log('Running RemoveCONFIGsav()')
- RMfiles = ['CONFIG.sav']
- Remove(RMfiles,'/etc/ptsenv/')
- def CheckUpdateSW():
- CheckSSH()
- Log('Running CheckUpdateSW() ')
- print(' Checking for (' + destination + ')\n')
- try:
- sftp.stat(destination)
- except IOError as e:
- if 'No such file' in str(e):
- print('update folder not found..')
- print('creating updatesw directory')
- logging.info('[' + time.strftime("%H:%M") + ']|> creating /tmp/updatesw')
- sftp.mkdir('/tmp/updatesw')
- print('proceeding to upgrade..')
- Upgrade()
- else:
- print('Folder already exists..\n')
- print('removing old folder')
- RemoveRemoteDir()
- print('folder removed\n')
- print('removing host IP from utility..')
- host = ''
- print('(host value should be blank)')
- print('host : ' + host)
- print('going back to menu...')
- PrintBox('unit already had update folder \nyou are about to return to menu \n please choose upgrade again')
- Clear()
- CheckUpdateSW()
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- def WindsorBackup():
- global SERIAL
- MapLDrive()
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> Entered WindsorBackup')
- os.chdir('L:\\')
- PrintDirs()
- if os.path.exists(str(SERIAL)):
- logging.info('[' + time.strftime("%H:%M") + ']|> ' + str(SERIAL) + ' is there!')
- else:
- CreateOSFolder([str(SERIAL)])
- logging.info('[' + time.strftime("%H:%M") + ']|> created ' + str(SERIAL))
- TimeStamp = time.strftime("%m_%d_%Y")
- Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
- if os.path.exists(Ldrive):
- logging.info('[' + time.strftime("%H:%M") + ']|> ' + Ldrive + 'was not found, will use hour and minute')
- #Ldrive = str(SERIAL)+'\\' +
- #time.strftime("%Y-%m-%d_%H-%M")+'\Pre_Wipe'
- TimeStamp = time.strftime("%m_%d_%Y[%H-%M]")
- Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
- CreateOSFolder([Ldrive])
- logging.info('[' + time.strftime("%H:%M") + ']|> new Ldrive .. ' + Ldrive)
- else:
- logging.info('[' + time.strftime("%H:%M") + ']|>' + Ldrive + 'was not found, creating it')
- CreateOSFolder([Ldrive])
- logging.info('[' + time.strftime("%H:%M") + ']|> creating rest of folders for backup')
- CreateOSFolder([Ldrive + '\Windsor_Backup',
- Ldrive + '\Windsor_Backup\etc', Ldrive + '\Windsor_Backup\etc\ptsenv', Ldrive + r'\Windsor_Backup\etc\unique',
- Ldrive + '\Windsor_Backup\\var', Ldrive + '\Windsor_Backup\\var\permalog',
- Ldrive + '\Windsor_Backup\home', Ldrive + '\Windsor_Backup\home\localdata'])
- PrintBox('Utility will now begin transferring files\n from unit to network drive...')
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to : ' + Ldrive)
- logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
- sftp.chdir('/etc/')
- os.chdir(Ldrive + '\Windsor_Backup\etc')
- path = 'ptsenv/'
- PrintDirs()
- print('Backing up ptsenv folder...')
- for filename in sftp.listdir('ptsenv'):
- if filename == 'BATTERY.log':
- logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
- cmd = 'rm ' + filename
- stdin, stdout, stderr = ssh.exec_command(cmd)
- elif filename != 'wpa_supplicant.d':
- if filename != 'BATTERY.log':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- path = 'unique/'
- PrintDirs()
- print('Backing up unique folder....')
- for filename in sftp.listdir('unique'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- sftp.chdir('/home/')
- os.chdir('home')
- PrintDirs()
- path = 'localdata/'
- print('Backing up localdata folder....')
- for filename in sftp.listdir('localdata'):
- if 'PTS' in filename:
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- sftp.chdir('/var/')
- os.chdir('var')
- path = 'permalog/'
- PrintDirs()
- print('Backing up permalog folder....')
- for filename in sftp.listdir('permalog'):
- if filename == 'lost+found':
- print('Removing lost+found')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing ' + path + 'lost+found')
- sftp.rmdir(path + 'lost+found')
- else:
- if filename != 'Templates':
- if filename != 'System Volume Information':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- wait()
- logging.info('[' + time.strftime("%H:%M") + ']|> finished pre wipe backup...')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing files...')
- Clear()
- def GuiFileCheck():
- Log('Checking for PTS GUI')
- cmd = 'ls /etc/ptsenv/'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- GuiFileSearch = stdout.read().strip().decode(encoding='utf-8')
- Log('contents of GuiFileSearch below... \n\n' + GuiFileSearch)
- if 'pts150gui2.ini' in GuiFileSearch:
- pass
- else:
- Log('pts150gui.ini not found in etc/petsenv/, creating file')
- stdin, stdout, stderr = ssh.exec_command("echo '[wifi]' >> /etc/ptsenv/pts150gui.ini")
- stdin, stdout, stderr = ssh.exec_command("UseWifi=false >> /etc/ptsenv/pts150gui.ini")
- def WifiNo():
- GuiFileCheck()
- Log('Setting Wifi to False')
- cmd = 'cat /etc/ptsenv/pts150gui.ini'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- WifiSearch = stdout.read().strip().decode(encoding='utf-8')
- Log('contents of pts150gui below... \n\n' + WifiSearch)
- if 'UseWifi=false' in WifiSearch:
- Log('WiFi already false')
- PrintBox('WiFI already enabled')
- elif 'UseWifi=true' in WifiSearch:
- Log('changing UseWifi to true..')
- cmd = "sed -i s/UseWifi=true/UseWifi=false/ /etc/ptsenv/pts150gui.ini"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Log('contents of pts150gui below... \n\n' + WifiSearch)
- else:
- Log('adding in UseWifi=false')
- cmd = r"sed -i '/\[wifi\]/,/\[wired\]/{ /^[[:space:]]*$/{ s//UseWifi=false\n/ } }' /etc/ptsenv/pts150gui.ini"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Log('contents of pts150gui below... \n\n' + WifiSearch)
- def WifiYes():
- Log('Setting Wifi to True')
- cmd = 'cat /etc/ptsenv/pts150gui.ini'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- WifiSearch = stdout.read().strip().decode(encoding='utf-8')
- Log('contents of pts150gui below... \n\n' + WifiSearch)
- if 'UseWifi=true' in WifiSearch:
- Log('WiFi already true')
- PrintBox('WiFI already enabled')
- elif 'UseWifi=false' in WifiSearch:
- Log('changing UseWifi to true..')
- cmd = "sed -i s/UseWifi=false/UseWifi=true/ /etc/ptsenv/pts150gui.ini"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Log('contents of pts150gui below... \n\n' + WifiSearch)
- else:
- Log('adding in UseWifi=true')
- cmd = r"sed -i '/\[wifi\]/,/\[wired\]/{ /^[[:space:]]*$/{ s//UseWifi=true\n/ } }' /etc/ptsenv/pts150gui.ini"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Log('contents of pts150gui below... \n\n' + WifiSearch)
- def WifiCheck():
- Clear()
- global _WifiAnswer_
- Log('Checking Wifi')
- cmd = 'lsusb'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- _wificheck = stdout.read().strip().decode(encoding='utf-8')
- Log('contents of lsusb below... \n\n' + _wificheck)
- ################ OLD CODE NOT NEEDED PER NEW CHECK METHOD ###########
- #_WifiAnswer_ = input('Is this a WiFi unit?(Y/N): ')
- #Log('user entered ' + _WifiAnswer_ + ' for ~is this wifi?~')
- #_confirm_ = input('You entered ' + _WifiAnswer_ + ' are you sure? ')
- #if _confirm_ == 'n':
- # Log('user chose N on confirm, starting WiFiCheck over')
- # WifiCheck()
- ####################################################################
- if 'Ralink' in _wificheck:
- pass
- else:
- if _WifiAnswer_ == 'y':
- Log('going to WifiYes()')
- WifiYes()
- else:
- Log('going to WifiNo()')
- WifiNo()
- def Upgrade():
- CheckSSH()
- WindsorBackup()
- LocalClean()
- PrintDirs()
- RemoveFactory()
- HomeFolder()
- EnableTest()
- RemoveCONFIGsav()
- # sftp.remove('/etc/ptsenv/CONFIG.sav')
- # PrintBox('removed CONFIG.sav')
- time.sleep(5)
- DisableTest()
- # ModeReplace()
- EnableTest()
- Log('Running Upgrade() ')
- print('Checking update directory')
- print(' Info on each file being worked on below..\n')
- for filename in os.listdir(source):
- print('____________________________\n')
- print(' working on \n' + filename + '\n')
- print(' moving.. \n' + os.path.join(source, filename) + '\n')
- print('to.. \n' + os.path.join(destination, filename) + '\n')
- print('(now doing actual command)')
- Log('moving update files from pc to nexgen')
- sftp.put(os.path.join(source, filename),
- os.path.join(destination, filename))
- print('____________________________\n')
- print('changing dir to update folder..')
- sftp.chdir('/tmp/updatesw')
- #####################################
- # #
- # -Installing packages- #
- # #
- #####################################
- PrintDirs()
- for filename in sftp.listdir(destination):
- filepath = os.path.join(destination, filename)
- PrintBox('Installing ... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> installing packages..')
- cmd = 'ipkg install -force-overwrite -force-downgrade ' + filepath
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Install = stdout.read().strip().decode(encoding='utf-8')
- print(Install)
- PrintBox('software installed..\n press any key to continue')
- m.getch()
- logging.info('[' + time.strftime("%H:%M") + ']|> sync after install')
- stdin, stdout, stderr = ssh.exec_command('sync')
- Sync = stdout.read().strip().decode(encoding='utf-8')
- print(Sync)
- DisableTest()
- SDFix()
- WifiCheck()
- Reboot()
- def MountCheck():
- CheckSSH()
- PrintDirs()
- Log('Running MountCheck() ')
- cmd = 'mount | grep ptsenv'
- #cmd = 'mount | grep i'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Mount = stdout.read().strip().decode(encoding='utf-8')
- if Mount == '':
- PrintBox(' Nothing mounted, moving to Install')
- logging.info('[' + time.strftime("%H:%M") + ']|> nothing found, moving to install')
- CheckUpdateSW()
- else:
- PrintBox('mount WAS NOT blank, doing copymount')
- logging.info('[' + time.strftime("%H:%M") + ']|> mount found, going to CopyMount()')
- #wait()
- CopyMount()
- MountCheck()
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- #####################################
- # #
- # _Files_ #
- # Nexgen -> PC #
- # #
- #####################################
- def CopyMount():
- HomeFolder()
- os.chdir('temp')
- sftp.chdir('/etc/')
- path = 'ptsenv/'
- Log('Running CopyMount()')
- PrintDirs()
- print('Backing up ptsenv folder...')
- for filename in sftp.listdir('ptsenv'):
- if 'root' not in filename:
- if '~' not in filename:
- if filename != 'default.cfg':
- if filename != 'wpa_supplicant.d':
- if filename != 'BATTERY.log':
- if filename != 'mode.cfg':
- print('filename is ' + filename)
- filepath = os.path.join(path, filename)
- print(' transferring... ' + filepath)
- print('_______________________________________\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- sftp.chdir('ptsenv')
- os.chdir('ptsenv')
- path = 'wpa_supplicant.d/'
- PrintDirs()
- print('Backing up wpa_supplicant.d folder...')
- for filename in sftp.listdir('wpa_supplicant.d'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- PrintDirs()
- HomeFolder()
- os.chdir('temp')
- sftp.chdir('/etc/')
- path = 'unique/'
- PrintDirs()
- print('Backing up unique folder....')
- for filename in sftp.listdir('unique'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- sftp.chdir('/home/')
- PrintDirs()
- path = 'localdata/'
- print('Backing up localdata folder....')
- for filename in sftp.listdir('localdata'):
- if 'PTS' in filename:
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- print('Sync Before Unmount')
- logging.info('[' + time.strftime("%H:%M") + ']|> sync before unmount')
- stdin, stdout, stderr = ssh.exec_command('sync')
- Sync = stdout.read().strip().decode(encoding='utf-8')
- print(Sync)
- #####################################
- # #
- # -unmountings- #
- # #
- #####################################
- PrintDirs()
- logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 5')
- print('umounting mtdblock5\n')
- cmd = 'umount /dev/mtdblock5'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Unmount5 = stdout.read().strip().decode(encoding='utf-8')
- print(Unmount5)
- print('MTDblock5 unmounted..\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 6')
- print('umounting mtdblock6\n')
- cmd = 'umount /dev/mtdblock6'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Unmount6 = stdout.read().strip().decode(encoding='utf-8')
- print(Unmount6)
- print('MTDblock6 unmounted...')
- logging.info('[' + time.strftime("%H:%M") + ']|> unmounting 7')
- print('umounting mtdblock7\n')
- cmd = 'umount /dev/mtdblock7'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- Unmount7 = stdout.read().strip().decode(encoding='utf-8')
- print(Unmount7)
- print('MTDblock7 unmounted...')
- logging.info('[' + time.strftime("%H:%M") + ']|> sync after unmount')
- print('Sync after Unmount...')
- stdin, stdout, stderr = ssh.exec_command('sync')
- Sync = stdout.read().strip().decode(encoding='utf-8')
- print(Sync)
- #####################################
- # #
- # _Files_ #
- # PC -> Nexgen #
- # #
- #####################################
- sftp.chdir('/etc/')
- path = 'ptsenv/'
- PrintDirs()
- print('deleting old ptsenv files from nexgen....')
- for filename in sftp.listdir('ptsenv'):
- if filename != 'wpa_supplicant.d':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n removing... ' + filepath)
- Log('Removing :' + filepath)
- sftp.remove(filepath)
- else:
- print('no file')
- print('restoring ptsenv files ....')
- for filename in os.listdir('ptsenv'):
- if filename != 'wpa_supplicant.d':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- sftp.put(filepath, filepath)
- else:
- print('no file')
- sftp.chdir('ptsenv')
- os.chdir('ptsenv')
- PrintDirs()
- path = 'wpa_supplicant.d/'
- try:
- sftp.stat('wpa_supplicant.d')
- except IOError as e:
- if 'No such file' in str(e):
- sftp.mkdir('wpa_supplicant.d')
- else:
- raise
- print('deleting old wpa_supplicant.d files to nexgen....')
- for filename in sftp.listdir('wpa_supplicant.d'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n removing... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- sftp.remove(filepath)
- else:
- print('no file')
- print('restoring wpa_supplicant.d files ....')
- PrintDirs()
- for filename in os.listdir('wpa_supplicant.d'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
- sftp.put(filepath, filepath)
- else:
- print('no file')
- os.chdir('..')
- sftp.chdir('/etc/')
- path = 'unique/'
- PrintDirs()
- print('deleting old unique files from nexgen....')
- for filename in sftp.listdir('unique'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n removing... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- sftp.remove(filepath)
- else:
- print('no file')
- print('restoring unique files ....')
- for filename in os.listdir('unique'):
- filepath = os.path.join(path, filename)
- logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- sftp.put(filepath, filepath)
- else:
- print('no file')
- sftp.chdir('/home/')
- path = 'localdata/'
- PrintDirs()
- print('deleting old localdata files from nexgen....')
- for filename in sftp.listdir('localdata'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n removing... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- sftp.remove(filepath)
- else:
- print('no file')
- print('restoring localdata files ....')
- for filename in os.listdir('localdata'):
- if 'PTS' in filename:
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> restoring :' + filepath)
- sftp.put(filepath,filepath)
- else:
- print('no file')
- print('Last Sync')
- logging.info('[' + time.strftime("%H:%M") + ']|> final sync')
- stdin, stdout, stderr = ssh.exec_command('sync')
- Sync = stdout.read().strip().decode(encoding='utf-8')
- print(Sync)
- print('finished copying files')
- #####################################
- # #
- # _Cleanup_ #
- # #
- #####################################
- def LocalClean():
- Clear()
- print('cleaning local files..')
- HomeFolder()
- os.chdir('temp')
- path = 'localdata/'
- print('removing localdata files from local computer...')
- for filename in os.listdir('localdata'):
- filepath = os.path.join(path, filename)
- print('Removing local file.. ' + filepath + '\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- os.remove(filepath)
- path = 'ptsenv/'
- print('removing ptsenv files from local computer...')
- for filename in os.listdir('ptsenv'):
- if filename != 'wpa_supplicant.d':
- filepath = os.path.join(path, filename)
- print('Removing local file.. ' + filepath + '\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- os.remove(filepath)
- path = 'unique/'
- print('removing unique files from local computer...')
- for filename in os.listdir('unique'):
- filepath = os.path.join(path, filename)
- print('Removing local file.. ' + filepath + '\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- os.remove(filepath)
- os.chdir('ptsenv')
- path = 'wpa_supplicant.d/'
- logging.info('removing wpa_supplicant.d files from local computer.....')
- print('removing wpa_supplicant.d files from local computer...')
- for filename in os.listdir('wpa_supplicant.d'):
- filepath = os.path.join(path, filename)
- print('Removing local file.. ' + filepath + '\n')
- print('Removing local file.. ' + filepath + '\n')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing :' + filepath)
- os.remove(filepath)
- Clear()
- def EnableTest():
- CheckSSH()
- Clear()
- HomeFolder()
- Log('enabling test mode')
- Log('checking inittab file..')
- cmd = 'tail /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- AppSearch = stdout.read().strip().decode(encoding='utf-8')
- if '#zd' in AppSearch:
- PrintBox('Unit already in test mode\n\n press any key to continue')
- else:
- cmd = 'sed -i s/zd:/#zd:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- stdin, stdout, stderr = ssh.exec_command('init q')
- PrintBox('Test mode is now ON \n\n press any key to continue')
- wait()
- def DisableTest():
- CheckSSH()
- Clear()
- HomeFolder()
- Log('disabling test mode')
- Log('checking inittab file..')
- cmd = 'tail /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- AppSearch = stdout.read().strip().decode(encoding='utf-8')
- if '#zd' in AppSearch:
- cmd = 'sed -i s/#zd:/zd:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- else:
- PrintBox('unit was not in test mode.')
- #----------------------------------------------
- #-- 01.Dec.16 -
- # ---------------------------------------------
- # Adding in catch for test mode set in mode.cfg
- cmd = 'cat /etc/ptsenv/MODE.cfg'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- AppSearch = stdout.read().strip().decode(encoding='utf-8')
- if '<entry key="TEST_MODE"><value>ON</value></entry>' in AppSearch:
- Log('Test Mode was enabled via MODE.cfg, disabling')
- cmd = "sed -i -e '/TEST_MODE/ s/ON/OFF/g' /etc/ptsenv/MODE.cfg"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- if '<checksum>' in AppSearch:
- Log('checksum exists in MODE.cfg, removing')
- cmd = "sed -i -e '/checksum/d' /etc/ptsenv/MODE.cfg"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- stdin, stdout, stderr = ssh.exec_command('init q')
- PrintBox('test mode disabled.')
- wait()
- def PuTTY():
- Clear()
- CheckSSH()
- Log('making sure unit is in test mode')
- cmd = 'tail /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- AppSearch = stdout.read().strip().decode(encoding='utf-8')
- if '#zd' in AppSearch:
- Log('unit already in test mode')
- PrintBox('Unit already in test mode')
- else:
- cmd = 'sed -i s/zd:/#zd:/ /etc/inittab'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- stdin, stdout, stderr = ssh.exec_command('init q')
- Log('enabled test mode')
- PrintBox('Test mode is now ON')
- Clear()
- os.system('color 17')
- PrintBox('launching putty, utility will progress once window is closed \n\n' + \
- 'Utility will disable test mode when putty is closed')
- winCMD = '.\putty.exe -ssh root@' + host + ' -pw ew3_llc'
- subprocess.call(winCMD)
- DisableTest()
- os.system('color 07')
- def MapLDrive():
- # initialize
- logging.info('[' + time.strftime("%H:%M") + ']|> started MapLDrive')
- driveLetter = 'L:'
- networkPath = '\\\\10.45.4.254\Data\\nexgen-PTS\\logs'
- # logging.info('[' + time.strftime("%H:%M") + ']|> drive letter is ' +
- # driveLetter + '..')
- #logging.info('[' + time.strftime("%H:%M") + ']|> path is ' + networkPath +
- #'..')
- # Disconnecting
- winCMD = 'NET USE ' + driveLetter + ' /delete /YES'
- logging.info('[' + time.strftime("%H:%M") + ']|> removing L: drive if it exists')
- #print(winCMD)
- subprocess.call(winCMD)
- # Mapping
- winCMD = 'NET USE ' + driveLetter + ' ' + networkPath
- logging.info('[' + time.strftime("%H:%M") + ']|> mapping L drive')
- #print(winCMD)
- subprocess.call(winCMD)
- Clear()
- def ClearWireless():
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> clearing wireless settings')
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- Clear()
- print('Removing wireless profiles')
- RMfiles = ['wpa_supplicant.conf']
- Remove(RMfiles,'/etc/')
- RMfiles = ['pts150gui.ini']
- Remove(RMfiles,'/etc/ptsenv/')
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- def ModeReplace():
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> entered ModeReplace()')
- Clear()
- try:
- sftp.stat('/etc/ptsenv/MODE.cfg')
- except IOError as e:
- if 'No such file' in str(e):
- print('no find found')
- sftp.put('MODE.cfg', '/etc/ptsenv/MODE.cfg')
- else:
- print('file found')
- sftp.remove('/etc/ptsenv/MODE.cfg')
- print('adding it back')
- sftp.put(UtilHome + '\MODE.cfg', '/etc/ptsenv/MODE.cfg')
- for filename in sftp.listdir('/etc/ptsenv/'):
- if filename == 'BATTERY.log':
- logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
- cmd = 'rm /etc/ptsenv/' + filename
- stdin, stdout, stderr = ssh.exec_command(cmd)
- _reboot = stdout.read().strip().decode(encoding='utf-8')
- stdin, stdout, stderr = ssh.exec_command('cmd')
- Clear()
- def RemoveConfig():
- Clear()
- HomeFolder()
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> running RemoveConfig().. ')
- RMfiles = ['SAMPLE_DB.cfg','LOT_CAL.cfg','PTSUSERS.cfg','DEFAULT.cfg']
- logging.info('[' + time.strftime("%H:%M") + ']|> RM files below... ')
- Remove(RMfiles,'/etc/ptsenv/')
- logging.info('[' + time.strftime("%H:%M") + ']|> cleaning user / adding default admin... ')
- cmd = 'echo "admin;427c6d6148ce09e80004096df96dfe6a224dbcf3;2;1;2016-01-01;2099-01-01" > /etc/ptsenv/PTSUSERS.cfg'
- stdin, stdout, stderr = ssh.exec_command(cmd)
- logging.info('[' + time.strftime("%H:%M") + ']|> file added... ')
- logging.info('[' + time.strftime("%H:%M") + ']|> files currently in ptsenv ')
- PrintBox('Cleaning out ptsenv files..')
- PrintDirs()
- path = '/etc/ptsenv/'
- for filename in sftp.listdir('/etc/ptsenv/'):
- if 'root' in filename:
- print(' removing ' + filename)
- sftp.remove(path + filename)
- if '~' in filename:
- print(' removing ' + filename)
- sftp.remove(path + filename)
- if filename == 'default.cfg':
- print(' removing ' + filename)
- sftp.remove(path + filename)
- if filename == 'DEFAULT.cfg':
- print(' removing ' + filename)
- sftp.remove(path + filename)
- # if filename == 'wpa_supplicant.d':
- # os.remove(filename)
- if filename == 'BATTERY.log':
- print(' removing ' + filename)
- sftp.remove(path + filename)
- # if filename == 'mode.cfg':
- # print(' removing ' + filename)
- # sftp.remove(path+filename)
- # do not need to replace MODE.cfg
- # ModeReplace()
- ClearWireless()
- Clear()
- def Copy2Remote():
- global SERIAL
- MapLDrive()
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> Entered Copy2Remote')
- os.chdir('L:\\')
- PrintDirs()
- if os.path.exists(str(SERIAL)):
- logging.info('[' + time.strftime("%H:%M") + ']|> ' + str(SERIAL) + ' is there!')
- else:
- CreateOSFolder([str(SERIAL)])
- logging.info('[' + time.strftime("%H:%M") + ']|> created ' + str(SERIAL))
- TimeStamp = time.strftime("%m_%d_%Y")
- Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
- if os.path.exists(Ldrive):
- logging.info('[' + time.strftime("%H:%M") + ']|> ' + Ldrive + 'was not found, will use hour and minute')
- #Ldrive = str(SERIAL)+'\\' +
- #time.strftime("%Y-%m-%d_%H-%M")+'\Pre_Wipe'
- TimeStamp = time.strftime("%m_%d_%Y[%H-%M]")
- Ldrive = 'L:\\' + str(SERIAL) + '\\' + TimeStamp
- CreateOSFolder([Ldrive])
- logging.info('[' + time.strftime("%H:%M") + ']|> new Ldrive .. ' + Ldrive)
- else:
- logging.info('[' + time.strftime("%H:%M") + ']|>' + Ldrive + 'was not found, creating it')
- CreateOSFolder([Ldrive])
- logging.info('[' + time.strftime("%H:%M") + ']|> creating rest of folders for backup')
- CreateOSFolder([Ldrive + '\Pre_Wipe',
- Ldrive + '\Pre_Wipe\etc', Ldrive + '\Pre_Wipe\etc\ptsenv', Ldrive + r'\Pre_Wipe\etc\unique',
- Ldrive + '\Pre_Wipe\\var', Ldrive + '\Pre_Wipe\\var\permalog',
- Ldrive + '\Pre_Wipe\home', Ldrive + '\Pre_Wipe\home\localdata'])
- PrintBox('Utility will now begin transferring files\n from unit to network drive...')
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to : ' + Ldrive)
- logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
- sftp.chdir('/etc/')
- os.chdir(Ldrive + '\Pre_Wipe\etc')
- path = 'ptsenv/'
- PrintDirs()
- print('Backing up ptsenv folder...')
- for filename in sftp.listdir('ptsenv'):
- if filename == 'BATTERY.log':
- logging.info('[' + time.strftime("%H:%M") + ']|> removing : ' + filename)
- cmd = 'rm ' + filename
- stdin, stdout, stderr = ssh.exec_command(cmd)
- _reboot = stdout.read().strip().decode(encoding='utf-8')
- stdin, stdout, stderr = ssh.exec_command('cmd')
- elif filename != 'wpa_supplicant.d':
- if filename != 'BATTERY.log':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- path = 'unique/'
- PrintDirs()
- print('Backing up unique folder....')
- for filename in sftp.listdir('unique'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- sftp.chdir('/home/')
- os.chdir('home')
- PrintDirs()
- path = 'localdata/'
- print('Backing up localdata folder....')
- for filename in sftp.listdir('localdata'):
- if 'PTS' in filename:
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- sftp.chdir('/var/')
- os.chdir('var')
- path = 'permalog/'
- PrintDirs()
- print('Backing up permalog folder....')
- for filename in sftp.listdir('permalog'):
- if filename == 'lost+found':
- print('Removing lost+found')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing ' + path + 'lost+found')
- sftp.rmdir(path + 'lost+found')
- else:
- if filename != 'Templates':
- if filename != 'System Volume Information':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- PrintBox('Please clear reports from Nexgen device')
- wait()
- logging.info('[' + time.strftime("%H:%M") + ']|> finished pre wipe backup...')
- logging.info('[' + time.strftime("%H:%M") + ']|> removing files...')
- RemoveConfig()
- for elem in sftp.listdir('/var/permalog/'):
- sftp.remove('/var/permalog/' + elem)
- os.chdir('L:\\')
- logging.info('[' + time.strftime("%H:%M") + ']|> L drive set to : ' + Ldrive)
- logging.info('[' + time.strftime("%H:%M") + ']|> creating subfolders...')
- CreateOSFolder([Ldrive + '\Post_Wipe',
- Ldrive + '\Post_Wipe\etc', Ldrive + '\Post_Wipe\etc\ptsenv', Ldrive + r'\Post_Wipe\etc\unique',
- Ldrive + '\Post_Wipe\\var', Ldrive + '\Post_Wipe\\var\permalog',
- Ldrive + '\Post_Wipe\home', Ldrive + '\Post_Wipe\home\localdata'])
- sftp.chdir('/etc/')
- os.chdir(Ldrive + '\Post_Wipe\etc')
- path = 'ptsenv/'
- PrintDirs()
- print('Backing up ptsenv folder...')
- for filename in sftp.listdir('ptsenv'):
- if filename == 'BATTERY.log':
- sftp.remove('BATTERY.log')
- elif filename != 'wpa_supplicant.d':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- path = 'unique/'
- PrintDirs()
- print('Backing up unique folder....')
- for filename in sftp.listdir('unique'):
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- sftp.chdir('/home/')
- os.chdir('home')
- PrintDirs()
- path = 'localdata/'
- print('Backing up localdata folder....')
- for filename in sftp.listdir('localdata'):
- if 'PTS' in filename:
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- sftp.chdir('/var/')
- os.chdir('var')
- path = 'permalog/'
- PrintDirs()
- print('Backing up permalog folder....')
- for filename in sftp.listdir('permalog'):
- if filename != 'Templates':
- if filename != 'System Volume Information':
- filepath = os.path.join(path, filename)
- PrintBox('filename is ' + filename + '\n transferring... ' + filepath)
- logging.info('[' + time.strftime("%H:%M") + ']|> backing up : ' + filepath)
- sftp.get(filepath, filepath)
- os.chdir('..')
- Clear()
- PrintBox('PTSenv & Permalog files backed up')
- HomeFolder()
- Reboot()
- Clear()
- def ImageCapture():
- CheckSSH()
- HomeFolder()
- sftp.chdir('/usr/local/bin')
- Log('Running ImageCapture() ')
- PrintBox('Capturing screenshot, please wait..')
- try:
- sftp.stat('fbimage')
- except IOError as e:
- Log('file not found, transferring now')
- sftp.put('fbimage','/usr/local/bin/fbimage')
- else:
- print('')
- time.sleep(5)
- Log('setting permissions')
- cmd = "chmod 777 /usr/local/bin/fbimage"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- setImage = stdout.read().strip().decode(encoding='utf-8')
- print(setImage)
- time.sleep(10)
- Log('taking screenshot')
- cmd = "/usr/local/bin/fbimage -d /dev/fb0 /usr/local/bin/image.png"
- stdin, stdout, stderr = ssh.exec_command(cmd)
- screenShot = stdout.read().strip().decode(encoding='utf-8')
- print(screenShot)
- PrintBox('Screenshot captured')
- Clear()
- HomeFolder()
- PrintBox('Transferring to computer..')
- screenCapture = './screenCaptures/' + SERIAL + '[' + time.strftime("%m_%d_%Y__%H-%M") + '].png'
- sftp.get('/usr/local/bin/image.png',screenCapture)
- time.sleep(5)
- im = Image.open(screenCapture)
- im.transpose(Image.ROTATE_90).save(screenCapture)
- sftp.remove('/usr/local/bin/image.png')
- def SendMail():
- # FROM = "Nexgen-Utility@crl.com"
- # TO = "Brandon.Dangerfield@crl.com"
- # Create message container - the correct MIME type is
- # multipart/alternative.
- Log('Sending Mail....')
- s = smtplib.SMTP('smtp.cr.local')
- msg = MIMEMultipart('alternative')
- #email list
- msg['Subject'] = "Nexgen-PTS ERROR [SERIAL - %s]" % (SERIAL)
- msg['From'] = 'Nexgen-Utility@crl.com'
- msg['To'] = "brandon.dangerfield@crl.com, jason.tremblay@crl.com"
- # Create the body of the message (a plain-text and an HTML version).
- text = """
- The system below has encountered an error
- 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.
- System Information1
- Serial : %s
- IP Address : %s
- System Version: %s
- App Version: %s
- """ % (SERIAL,host,Version_System,Version_App)
- html = """\
- <html>
- <head></head>
- <body>
- The system below has encountered an error<br>
- The log file attached may not be up to date! <br><br>
- <table>
- <tr>
- <th colspan="2"><b><u><h1>System Information</h1></u></b></th>
- </tr>
- <tr>
- <td><b>Serial</b></td>
- <td>%s</td>
- </tr>
- <tr>
- <td><b>IP Address</b></td>
- <td>%s</td>
- </tr>
- <tr>
- <td><b>System Version</b></td>
- <td>%s</td>
- </tr>
- <tr>
- <td><b>App Version</b></td>
- <td>%s</td>
- </tr>
- </table>
- </body>
- </html>
- """ % (SERIAL,host,Version_System,Version_App)
- # Record the MIME types of both parts - text/plain and text/html.
- part1 = MIMEText(text, 'plain')
- part2 = MIMEText(html, 'html')
- part3 = MIMEApplication(open(Logname,"rb").read())
- part3.add_header('Content-Disposition', 'attachment', filename=Logname)
- # Attach parts into message container.
- # According to RFC 2046, the last part of a multipart message, in this case
- # the HTML message, is best and preferred.
- msg.attach(part1)
- msg.attach(part2)
- msg.attach(part3)
- # sendmail function takes 3 arguments: sender's address, recipient's
- # address
- # and message to send - here it is sent as one string.
- s.sendmail(msg['From'],["brandon.dangerfield@crl.com", "jason.tremblay@crl.com"], msg.as_string())
- s.quit()
- def ResizeWindow():
- os.system('mode con: cols=90 lines=75')
- #s = smtplib.SMTP('smtp.uk.xensource.com')
- #s.set_debuglevel(1)
- #msg = MIMEText("""body""")
- ##sender = 'me@example.com'
- #recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
- #msg['Subject'] = "subject line"
- #msg['From'] = sender
- ##msg['To'] = ", ".join(recipients)
- #s.sendmail(sender, recipients, msg.as_string())
- #################################
- # #
- # Options / ETC below #
- # #
- #################################
- CreateOSFolder(['screenCaptures','logs','temp','temp/unique','temp/ptsenv','temp/ptsenv/wpa_supplicant.d','temp/localdata'])
- #Logging
- Logname = './logs/Nexgen_Utility_Log_' + (time.strftime("%Y-%m-%d_%H-%M") + '.log')
- logging.basicConfig(filename=Logname,level=logging.INFO)
- logging = logging.getLogger(__name__)
- def main():
- Options()
- def Options():
- Clear()
- # ResizeWindow()
- Log('Loading main...' + '\n' + ' ' + '\n' + ' Host : ' + host + '\n' + ' App Version :' + Version_App + '\n' + ' Serial Number : ' + SERIAL + '\n')
- print("""
- ______________________________________
- | |
- | Nexgen Update Utility |
- | v 1.4 |
- |_____________________________________|
- Validated to install/upgrade
- version 10.2 and earlier releases
- """)
- print(' The current working directory...')
- print(' ' + os.getcwd())
- PrintBox(' IP Address : ' + host + \
- '\nApplication version : ' + Version_App + \
- # '\n System Version : '+ Version_System + \
- '\n Serial Number : ' + SERIAL)
- menu = {}
- print('Please choose one of the options below...\n')
- menu['[1]'] = "Set or Change IP Address"
- menu['[2]'] = "Get Set Point Value"
- menu['[3]'] = "Upgrade"
- menu['[4]'] = "Enable Test mode"
- menu['[5]'] = "Disable Test Mode"
- menu['[6]'] = "Backup files & Clean Unit \n______________________\n"
- menu['[7]'] = "Fix Config.sav"
- menu['[8]'] = "Take Screenshot \n______________________\n"
- menu['[9]'] = "Launch PuTTY \n______________________\n"
- #menu['[w]'] = "Set Wifi Model"
- menu['[x]'] = "Exit"
- while True:
- main = list(menu.keys())
- main.sort()
- for entry in main:
- print(entry, menu[entry])
- selection = input("\nPlease Select: ")
- if selection == "1":
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [1]...')
- Clear()
- GetHost()
- Options()
- elif selection == '2':
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [2]...')
- Clear()
- GetTemp()
- Options()
- elif selection == '3':
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [3]...')
- Clear()
- #CheckUpdateSW()
- MountCheck()
- #Reboot()
- Options()
- elif selection == '4':
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [4]...')
- Clear()
- EnableTest()
- CheckSD()
- Options()
- elif selection == '5':
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [5]...')
- Clear()
- DisableTest()
- Options()
- elif selection == '6':
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [6]...')
- CheckSSH()
- CheckSD()
- Copy2Remote()
- Options()
- elif selection == '7':
- Log('User selected [7]')
- Clear()
- EnableTest()
- sftp.remove('/etc/ptsenv/CONFIG.sav')
- Clear()
- DisableTest()
- Options()
- elif selection == '8':
- Log('User selected [8]')
- Clear()
- ImageCapture()
- Clear()
- Options()
- elif selection == '9':
- Log('User selected [9]')
- Clear()
- PuTTY()
- Options()
- elif selection == '77':
- Log('User selected [77]')
- SendMail()
- Options()
- #elif selection == 'w':
- # Log('User selected [w]')
- #WifiCheck()
- # Options()
- elif selection == 'x':
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> User selected [99]...')
- logging.info('[' + time.strftime("%H:%M") + ']|> CLOSING...')
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- exit()
- elif selection == 't':
- RemoveConfig()
- Options()
- else:
- print("\nUnknown Option Selected!\n")
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- logging.info('[' + time.strftime("%H:%M") + ']|> User input invalid selection...')
- logging.info('[' + time.strftime("%H:%M") + ']|> ________________________________________')
- wait()
- Clear()
- Options()
- #####################################
- # #
- # -Calling Functions- #
- # #
- #####################################
- Clear()
- if __name__ == Options():
- Options()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement