Sign in to follow this  
Followers 0
Colyn1337

Automatic Firmware Updates - SQLite & WMI

1 post in this topic

#1 ·  Posted (edited)

#cs -----------------------------------------------------------------------------------------------------------------
Author:
Colyn Via
Script Function:
Query local device WMI info and perform a SQL lookup to check for firmware updates. The SQL database contains
device models, current firmware version, and the path to the update package. This script looks for the firmware
version based on the device model, and then copies the installer to the host drive. The script then performs a
silent install of the firmware update all the while preventing an accidental shutdown. This script has a verbose
log which gets copied to a network location if there's a problem. If it's successful the log writes a single
line to a master log in the same network location reporting it's success. Once the update is complete, the
installer file is deleted, as well as the local log file.
Version Notes:
1.0.03 - Adjusted final write to local log so that the $FirmwareDBResult is written in the log.
1.0.02 - Added processwait() to script to prevent premature script completion
1.0.01 - Added values to BIOSString dump in addition to names
1.0.00 - Initial complete version
#ce -----------------------------------------------------------------------------------------------------------------
#NoTrayIcon
#include 
#include 
; Unless directed otherwise, autoit will do an internet lookup for the driver to use. Later in the code
; the _SQLite_Startup UDF directs the program to get the driver locally. This is why it's important to
; include the driver in the package.
FileInstall("SQLite3.dll", @ScriptDir & "", 1)
Global $FWversion, $Product, $hDB, $hQuery, $aRow, $UpgradeDBResult, $FWversionDBResult, $CheckCurrent
Global $CheckDB, $UpgradeEXE, $SQLQuery1, $SQLQuery2, $PID
Global Const $Timestamp = @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & " "
Global Const $Log = "C:AMTFirmwareLog_" & @ComputerName & ".txt"
Global Const $GlobalLog = 'redactedvProFirmware ResponsesSuccessSucceeded.txt'
Global Const $FirmwareDB = 'redactedvProFirmware.db'
Global Const $GlobalResponse = 'redactedvProFirmware Responses'
; This script was designed to be verbose and log most events. This code creates the log and adds the first line.
FileWriteLine($Log, $Timestamp & "Hello! My name is " & @ComputerName & ". " & @OSVersion & " " & @OSArch & " is how I roll.")
FileWriteLine($Log, $Timestamp & "I'm running script 1.0.03.")
FWversion()
; This function runs a WMI query to get the current AMT firmware version on the device.
Func FWversion()
$objIntelME = ObjGet("winmgmts:" & "." & "rootIntel_ME")
; An error catch must be present here, as AutoIt does not mute COM errors naturally. Without this catch,
; an ugly sounding error will appear to the user. IsObj() is not enough, as it cannot handle a return.
If @error Then
FileWriteLine($Log, $Timestamp & "Intel_ME is not a valid NAMESPACE.")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
Exit
EndIf
$colIntelME = $objIntelME.ExecQuery("SELECT * FROM ME_System")
; The "Else" of this statement reports back which devices couldn't determine their firmware version.
If IsObj($colIntelME) Then
For $objMEsystem In $colIntelME
$FWversion = $objMEsystem.fwversion
Next
Else
FileWriteLine($Log, $Timestamp & "ME_System query failed.")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
Exit
EndIf
FileWriteLine($Log, $Timestamp & "Local host vPro firmware lookup result = " & $FWversion)
ConsoleWrite("Local host vPro firmware lookup result = " & $FWversion & @LF)
EndFunc ;==>FWversion
Product()
; This function runs a WMI query to get the current model information for the device.
Func Product()
; Since these variables are used often in general coding practice, they are Local'd instead of
; declared global. When the code finishes this function, it will drop these variables.
Local $x, $y, $prodArray, $aRefine
$objWMI = ObjGet("winmgmts:" & @ComputerName & "rootHPInstrumentedBIOS")
If @error Then
FileWriteLine($Log, $Timestamp & "rootHPInstrumentedBIOS is not a valid NAMESPACE.")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
Exit
EndIf
$colItems = $objWMI.ExecQuery("SELECT * FROM HPBIOS_BIOSString")
; The "Else" of this block accounts for the possibility that this code might run on a non HP device.
If IsObj($colItems) Then
FileWriteLine($Log, $Timestamp & "Attempting to grab hardware info.")
For $objItems In $colItems
If $objItems.Name = "Notebook Model" Then
$Product = $objItems.Value
FileWriteLine($Log, $Timestamp & "Raw value for " & $objItems.Name & " is " & $Product)
$prodArray = StringSplit($Product, " ")
; BIOS revisions change slightly how the information is presented by WMI. Sometimes it's
; simply the Model number, other times it can be a string of words. For simplicity and
; uniformity, this code strips out just the Model number from the string. This code is
; looking for a word that starts with a number. If HP begins using Model Numbers that
; start with letters, this code will need to be reworked.
For $x = 1 To $prodArray[0]
If StringIsAlpha($prodArray[$x]) Then
Else
; As it turns out, HP in its infinite wisdom decided to, in some cases, put both
; product identifiers in the SAME CIM component value. This confuses the scrip and
; it ends up recording the wrong value. To correct for this, and as the model
; number always starts with a number (currently), I've directed the script to check
; the first character in the string it's wanting to use to see if it's a number
; IsInt means "is it an integer", which in this case, the value is not. AutoIt
; sees it as a string, so Number() is used instead.
FileWriteLine($Log, $Timestamp & "I'm considering using " & $prodArray[$x] & ".")
$aRefine = StringSplit($prodArray[$x], "")
If Number($aRefine[1]) Then
FileWriteLine($Log, $Timestamp & "It turns out that " & $prodArray[$x] & " starts with " & $aRefine[1] & _
" and must therefore be what I'm looking for. Right?")
$Product = ($prodArray[$x])
EndIf
EndIf
Next
ExitLoop
ElseIf $objItems.Name = "Product Name" Then
$Product = $objItems.Value
FileWriteLine($Log, $Timestamp & "Raw value for " & $objItems.Name & " is " & $Product)
$prodArray = StringSplit($Product, " ")
For $x = 1 To $prodArray[0]
If StringIsAlpha($prodArray[$x]) Then
Else
FileWriteLine($Log, $Timestamp & "I'm considering using " & $prodArray[$x] & ".")
$aRefine = StringSplit($prodArray[$x], "")
If Number($aRefine[1]) Then
FileWriteLine($Log, $Timestamp & "It turns out that " & $prodArray[$x] & " starts with " & $aRefine[1] & _
" and must therefore be what I'm looking for. Right?")
$Product = ($prodArray[$x])
EndIf
EndIf
Next
ExitLoop
EndIf
Next
FileWriteLine($Log, $Timestamp & "Finished attempts to grab hardware info.")
; In the event that "Notebook Model" is not the value to read, it helps to see what should be added.
; The following code runs a dump of the contents of HPBIOS_BIOSstring and copies the log to the log directory.
; Later the results of the log can be used to determine what other $objItems.Name might exist.
If $Product = "" Then
FileWriteLine($Log, $Timestamp & "Query (SELECT * FROM HPBIOS_BIOSString) SUCCEEDED! However unable to " & _
"resolve object.name of known variables on " & @ComputerName & ".")
FileWriteLine($Log, "*************** Beginning Dump of HPBIOS_BIOSstring ***************")
For $objItems In $colItems
FileWriteLine($Log, "*** " & $objItems.name & " = " & $objItems.Value)
Next
FileWriteLine($Log, "*************** Done Exporting HPBIOS_BIOSstring ***************")
Sleep(5)
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
Exit
EndIf
Else
FileWriteLine($Log, $Timestamp & "rootHPInstrumentedBIOS is not a valid NAMESPACE on " & @ComputerName & ".")
EndIf
ConsoleWrite("WMI query for Model produced " & $Product & @LF)
EndFunc ;==>Product
If $FWversion = "" Then Exit
If $Product = "" Then Exit
SQL()
; This function names the SQL queries and initializes the SQL engine.
Func SQL()
; SQL Queries
$SQLQuery1 = "SELECT " & '"' & "Update" & '"' & " FROM Lookup WHERE Product=" & '"' & $Product & '"' & ';'
$SQLQuery2 = "SELECT " & '"' & "FWVersion" & '"' & " FROM Lookup WHERE Product=" & '"' & $Product & '"' & ';'
; Check the DB and open it if the script can find it
FileWriteLine($Log, $Timestamp & "Checking to see if " & '"' & $FirmwareDB & '"' & " exists...")
If FileExists($FirmwareDB) Then
FileWriteLine($Log, $Timestamp & "Found it!")
Else
FileWriteLine($Log, $Timestamp & "I can't see it!")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
Exit
EndIf
_SQLite_Startup("", "", 0)
_SQLite_Open($FirmwareDB)
EndFunc ;==>SQL
Eligibility()
; This function determines the devices eligibility to upgrade, and figures out where to get the update from.
Func Eligibility()
; Since these variables are used often in general coding practice, they are Local'd instead of
; declared global. When the code finishes this function, it will drop these variables.
Local $x, $y, $z, $Proceed, $diff, $exe
_SQLite_Query(-1, $SQLQuery1, $hQuery)
If _SQLite_FetchData($hQuery, $aRow) = $SQLITE_OK Then
Else
ConsoleWrite("Query Failed")
FileWriteLine($Log, $Timestamp & $SQLQuery1 & " FAILED.")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
_SQLite_QueryFinalize($hQuery)
_SQLite_Close()
_SQLite_Shutdown()
Exit
EndIf
$UpgradeDBResult = $aRow[0]
FileWriteLine($Log, $Timestamp & $SQLQuery1 & " SUCCEEDED.")
_SQLite_QueryFinalize($hQuery)
ConsoleWrite($UpgradeDBResult & @LF)
; Need to get just the name of the update executable for use later.
$exe = StringSplit($UpgradeDBResult, "")
$UpgradeEXE = $exe[($exe[0])]
FileWriteLine($Log, $Timestamp & "The executable needed later is " & $UpgradeEXE & ".")
; Testing purposes - Making my host appear to be a 6550b
;~ $SQLQuery2 = "SELECT " & '"' & "FWVersion" & '"' & " FROM Lookup WHERE Product=" & '"' & "6550b" & '"' & ';'
_SQLite_Query(-1, $SQLQuery2, $hQuery)
If _SQLite_FetchData($hQuery, $aRow) = $SQLITE_OK Then
Else
ConsoleWrite("Query Failed")
FileWriteLine($Log, $Timestamp & $SQLQuery2 & " FAILED.")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
_SQLite_QueryFinalize($hQuery)
_SQLite_Close()
_SQLite_Shutdown()
Exit
EndIf
$FWversionDBResult = $aRow[0]
FileWriteLine($Log, $Timestamp & $SQLQuery2 & " SUCCEEDED.")
_SQLite_QueryFinalize($hQuery)
ConsoleWrite($FWversionDBResult & @LF)
FileWriteLine($Log, $Timestamp & "Query result was " & $FWversionDBResult)
; Be sure to close down SQL when it's not needed.
_SQLite_Close()
_SQLite_Shutdown()
; Testing purposes - Make my firmware appear older
;~ $FWversion = "6.2.0.1022"
FileWriteLine($Log, $Timestamp & "Comparing firmware versions.")
; So as not to run the risk of destroying the data, the data is copied to new
; variables before be begin to break it apart into arrays.
$CheckCurrent = StringSplit($FWversion, ".")
$CheckDB = StringSplit($FWversionDBResult, ".")
FileWriteLine($Log, $Timestamp & "Splitting firmware strings.")
; This code checks to make sure the two arrays are equal in terms of size.
; If they are not, the code will generate an error. This code also manually
; adjusts either array so that it always matches the larger of the two.
If $CheckDB[0] > $CheckCurrent[0] Then
$diff = ($CheckDB[0] - $CheckCurrent[0])
For $z = 1 To $diff
_ArrayAdd($CheckCurrent, 0)
Next
EndIf
If $CheckDB[0] < $CheckCurrent[0] Then
$diff = ($CheckCurrent[0] - $CheckDB[0])
For $z = 1 To $diff
_ArrayAdd($CheckDB, 0)
Next
EndIf
FileWriteLine($Log, $Timestamp & "Finished comparing stringsplit array sizes, continuing to determine if upgrade is needed.")
; This part is checking to see if the firmware update indicated by the SQL query
; is newer than the current version on the device. If the firmware is current or
; better, the program deletes the log file and closes.
Do
For $x = 1 To $CheckDB[0]
If $CheckDB[$x] > $CheckCurrent[$x] Then
$Proceed = "y"
ExitLoop
ElseIf $CheckDB[$x] < $CheckCurrent[$x] Then
$Proceed = "n"
ExitLoop
ElseIf $CheckDB[$x] = $CheckCurrent[$x] And $x = $CheckDB[0] Then
$Proceed = "n"
ExitLoop
EndIf
Next
Until $Proceed <> ""
If $Proceed = "n" Then
FileDelete($Log)
Exit
EndIf
FileWriteLine($Log, $Timestamp & "Finished comparing firmware versions. Proceeding to UpdateFirmware()")
EndFunc ;==>Eligibility
; $UpgradeDBResult is the path to the firmware update as retrieved by the Eligibility() function
UpdateFirmware()
; This function pulls down the update and executes it. It also writes to the $GlobalLog.
Func UpdateFirmware()
FileWriteLine($Log, $Timestamp & "Attempting to copy " & '"' & $UpgradeDBResult & '"' & " to local drive.")
If FileExists($UpgradeDBResult) Then
FileCopy($UpgradeDBResult, @HomeDrive & "")
Else
FileWriteLine($Log, $Timestamp & "FileExists() check failed. I quit!")
FileCopy($Log, $GlobalResponse)
FileDelete($Log)
Exit
EndIf
FileWriteLine($Log, $Timestamp & "Run command issued for " & @HomeDrive & "" & $UpgradeEXE)
; The -s switch is for silent install
Run(@HomeDrive & "" & $UpgradeEXE & " -s", "", @SW_HIDE)
; Prevent shutdown during firmware update process
ProcessWait($UpgradeEXE, 60)
Do
Run("shutdown /a", @SystemDir, @SW_HIDE)
Sleep(10)
$PID = ProcessExists($UpgradeEXE)
Until $PID = 0
FileWriteLine($GlobalLog, $Timestamp & @ComputerName & " launched " & $UpgradeEXE & " to achieve " & $FWversionDBResult & ".")
EndFunc ;==>UpdateFirmware
FileDelete(@HomeDrive & "" & $UpgradeEXE)
FileDelete($Log)
Exit

Edited by Colyn1337

Share this post


Link to post
Share on other sites



Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • 9252Survive
      By 9252Survive
      Hi All, 
       
      I am fairly new to AutoIT and I am still trying to learn, I have been using _FileListToArray to list all the files with a particular extension in an array and then loop through it for operation  (   For $i = 1 To UBound($FileArray) - 1).
      So far this has been working fine. But I am not able to figure out a problem that I have; what if I have 50 files but I only want to loop through first 10 files and then next ten and so on?  Or rather I should say, how I can I only feed max 10 files to the array at a time when I do _FileListToArray regardless of the total number of files in the folder?
      Any insight/help will be much appreciated 
    • ModemJunki
      By ModemJunki
      Hello,
      In Windows 10 PowerShell, one can do this to change the metric for a NIC in Windows 10:
      Get-NetAdapter | Where-Object -FilterScript {$_.InterfaceAlias -Eq "Ethernet 2"} | Set-NetIPInterface -InterfaceMetric 2 I know I can script the above PowerShell line (and it works!), but I wanted to try something I hadn't done before after looking into jguinch's most excellent Network configuration UDF. I wanted to make use of the SetIPConnectionMetric method in the WMI classes. There is an example VBscript here but this is not for Windows 10. Using AutoIT would also give better control over capturing error return codes than with PowerShell.
      But I cannot get my script to work! The return from SetIPConnectionMetric() is 0, which would indicate success. Yet the change does not happen. I also tried WMI methods using .put_ but this fails.
      Anyone more experienced than I have ideas to make this work?
      #RequireAdmin _SetNicInterfaceMetric2("Ethernet 2", "2") Func _SetNicInterfaceMetric2($NIC_NAME, $METRIC) Local $s_setIndx = 0 $objWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2") $colNICItems = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & $NIC_NAME & "'", "WQL") If IsObj($colNICItems) Then For $objItem In $colNICItems $s_nicIndex = $objItem.Index Next ConsoleWrite("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = '" & $s_nicIndex & "'" & @CRLF) $colNAC = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = '" & $s_nicIndex & "'", "WQL") If IsObj($colNAC) Then For $objNetCard In $colNAC If $METRIC <> $objNetCard.IPConnectionMetric Then ConsoleWrite("Metric was set to " & $objNetCard.IPConnectionMetric & ". Setting to " & $METRIC & "." & @CRLF) $s_isSet = $objNetCard.SetIPConnectionMetric($METRIC) ConsoleWrite("SetIPConnectionMetric Result = " & $s_isSet & @CRLF) Else ConsoleWrite("Metric is already set to " & $METRIC & @CRLF) EndIf Next EndIf EndIf EndFunc ;==>_SetNicInterfaceMetric2  
    • AndyS19
      By AndyS19
      I have code that does a WMI SQL query to find all defined printers, and I want to parse the returned object in several places.  However, after parsing it the first time, all other times fail to find any printer objects.
      Here is my test code:
      test() Func test() Local $oPrinters, $oPrinter, $err, $cnt, $oP, $query $query = "SELECT * FROM Win32_Printer" $oPrinters = doQuery($query) $err = @error LogMsg("+++: $err = " & $err & ", isObj($oPrinters) = " & IsObj($oPrinters)) If ($err == 0) Then LogMsg("FIRST LOOP") ; <=== FIRST LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") LogMsg("SECOND LOOP") ; <== SECOND LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") EndIf EndFunc ;==>test Func doQuery($sQuery, $lnum = @ScriptLineNumber) #forceref $lnum LogMsg("+++:" & $lnum & ": doQuery(" & '"' & $sQuery & '"' & ") entered") Local $oWMIService, $oResults, $errstr Local $wbemFlags = BitOR(0x20, 0x10) ; $wbemFlagReturnImmediately and wbemFlagForwardOnly $oWMIService = ObjGet("winmgmts:\\" & "localhost" & "\root\CIMV2") If (IsObj($oWMIService)) Then $oResults = $oWMIService.ExecQuery($sQuery, "WQL", $wbemFlags) If (IsObj($oResults)) Then LogMsg("+++: doQuery() returns @error = 0, Good: returning the object") Return (SetError(0, 0, $oResults)) ;;; Good: return the object Else $errstr = "" _ & "WMI Query failed." & @CRLF _ & "This is the query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") LogMsg("+++: doQuery() returns @error = 1") Return (SetError(1, 0, $errstr)) ; Error: Query faled EndIf Else $errstr = "" _ & "WMI Output" & @CRLF _ & "No WMI Objects Found for class: " & @CRLF _ & "Win32_PrinterDriver" & @CRLF _ & "using this query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") MsgBox(0, "ERROR", $errstr) ; Error: Cannot get $oWMIService object Exit (1) EndIf EndFunc ;==>doQuery Func LogMsg($msg, $lnum = @ScriptLineNumber) ConsoleWrite("+++:" & $lnum & ": " & $msg & @CRLF) EndFunc ;==>LogMsg Parsing the returned $oPrinters object shows 5 printers:
      +++:15: FIRST LOOP +++:18: +++: isObj($oP) = 1 +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft XPS Document Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft Office Document Image Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Fax<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG7100 series Printer WS<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG6100 series Printer WS<== +++:24: +++: Found 5 printers Parsing it again, shows no printers:
      +++:26: SECOND LOOP +++:29: +++: isObj($oP) = 1 +++:35: +++: Found 0 printers  
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening guys
      I am working on a little project, in which I have to retrieve 8000+ rows of data from a table, from a SQLite database, to populate a combobox 
      This is what I tried 'til now, but it still takes about 12 seconds to populate the combobox.
      _SQLite_Exec($objDatabase, "BEGIN TRANSACTION;") If _SQLite_GetTable($objDatabase, "SELECT DISTINCT Comune FROM LISTA_COMUNI;", $arrRisultatoQuery, $intRighe, $intColonne) = $SQLITE_OK Then For $i = 2 To UBound($arrRisultatoQuery) - 1 If $i < UBound($arrRisultatoQuery) - 1 Then GUICtrlSetData($cbo_ComuneNascita, $arrRisultatoQuery[$i] & "|") Else GUICtrlSetData($cbo_ComuneNascita, $arrRisultatoQuery[$i]) EndIf Next _SQLite_Exec($objDatabase, "COMMIT;") Are there any other solution to retrieve 8000+ records from a SQLite database?
      Thank you very much  
    • NiftRex
      By NiftRex
      I'm trying to get an array from a website so that I can just get the url, but I am not sure how. I read a bit of arrays but I have a feeling I'd have to be writing a lot more than what I should be. I will include the script I have so far and the API url for what I want.
       
      API: https://api.fast.com/netflix/speedtest?https=true&token=YXNkZmFzZGxmbnNkYWZoYXNkZmhrYWxm&urlCount=1 (I want the 'url' array that contains the url)
       
      Code:
      #include <MsgBoxConstants.au3> #include <Inet.au3> #include <Array.au3> $site = _INetGetSource('http://api.fast.com/netflix/speedtest?https=true&token=YXNkZmFzZGxmbnNkYWZoYXNkZmhrYWxm&urlCount=1') MsgBox($MB_SYSTEMMODAL, "Title", $site[1])