methyltryp

launchNBME

Aug 27th, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3.     <#
  4.  
  5.     Script to download the secure web browser for NBME, and reduce as much as possible
  6.     the chance of the secure exam being interrupted by external variables. This is to
  7.     get the NBME exam to load and the tests to be ready with as little input from the
  8.     operator as possible
  9.  
  10.     Written for UNM SOM UME ETS
  11.     Version 2.1.11032015
  12.  
  13.     #>
  14.  
  15.  
  16.     #Check to make sure we're connected to a netowrk. If not, see if HSC_Guest is available,
  17.     #and then try and auto-connect to that.
  18.  
  19.    
  20.    
  21.     function Clean-Quit { #leave the script gracefully
  22.         try
  23.         {
  24.         Write-Host "Press Y to Shutdown, or Press Any Other Key to Exit..." -BackgroundColor Green -ForegroundColor White
  25.         $WaitKeypress = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | select character -expand character
  26.         if ( $WaitKeypress -eq 'y' ) { Stop-Computer }
  27.         }
  28.         catch
  29.         {
  30.         Write-Host "Actually, never mind. I lied. You need to close this window to exit." -BackgroundColor Blue -ForegroundColor red
  31.         }
  32.         exit
  33.     }
  34.  
  35.     function Dirty-Quit { #something bad went down
  36.         param([string]$Reason)
  37.         Write-Host $Reason -BackgroundColor Red -ForegroundColor White
  38.         try
  39.         {
  40.         $WaitKeypress = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  41.         }
  42.         catch {}
  43.         exit
  44.         }
  45.  
  46.        
  47.    
  48.     function Get-Networks { #return a string with the network SSID or LAN
  49.         $SSID = netsh wlan show interfaces | findstr /r "^....SSID"
  50.         $netInfo = Get-WmiObject win32_networkadapter -filter "netconnectionstatus = 2" | select netconnectionid -expand netconnectionid
  51.         if ($netInfo.count -eq 0) { return $false }
  52.         elseif ($netInfo -contains "Local Area Connection") { return "Local Area Connection" }
  53.         else { return [string]$SSID.SubString(29) }
  54.     }
  55.  
  56.    
  57.  
  58.     function Query-NTP { #Get the internet time from time.nist.gov. Probably won't work with anywhere else.
  59.         $TcpClient = New-Object System.Net.Sockets.TcpClient
  60.         [byte[]]$buffer = ,0 * 64
  61.         try
  62.         {
  63.         $TcpClient.Connect('time.nist.gov',13)
  64.         }
  65.         catch
  66.         {
  67.         return $false
  68.         }
  69.         $TcpStream = $TcpClient.GetStream()
  70.         $length = $TcpStream.read($buffer, 0, $buffer.length)
  71.         [void]$TcpClient.Close()
  72.         if ($length -gt 0) {
  73.             $raw = [Text.Encoding]::ASCII.GetString($buffer)
  74.             return [DateTime]::ParseExact($raw.SubString(7,17),'yy-MM-dd HH:mm:ss', $null).toLocalTime()
  75.         } else {
  76.             return $false
  77.         }
  78.     }
  79.  
  80.     Function Check-Time { #Check that our computer time matches official time (NBME's browser is date-based, I don't care about am/pm)
  81.         Write-Host "Attempting to check for correct system Date/Time"
  82.         $ntpTime = Query-NTP | Out-String
  83.         $LocalTime = get-date | Out-String
  84.         if ($ntpTime.Length -ge 24) { $ntpTime = $ntpTime.SubString(1,24) }
  85.         else {  return "Unable to successfully query NTP. Disregarding." }
  86.         $LocalTime = $LocalTime.SubString(1,24)
  87.         if ($LocalTime -eq $ntpTime) {
  88.             Write-Host "System Date/Time is correct." -ForegroundColor Green
  89.         } else {
  90.             Write-Host "Incorrect system date. Download will most likely fail." -BackgroundColor Yellow -ForegroundColor White #we don't quit, because it's probs nothing
  91.        }
  92.     }
  93.  
  94.     function Check-Activation { #check windows activation state. Will eventually automatically activate windows. Not really necessary for us anymore, but left it in for funsies.
  95.         $licenseStatus=@{0="Unlicensed"; 1="Licensed"; 2="OOBGrace"; 3="OOTGrace"; 4="NonGenuineGrace"; 5="Notification"; 6="ExtendedGrace"}
  96.         $ActStatus = Get-CimInstance -Class SoftwareLicensingProduct | Where {$_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" -AND $_.PartialProductKey -ne $null}
  97.         return $licenseStatus[[int]$ActStatus.LicenseStatus]
  98.     }
  99.  
  100.  
  101.     function Check-Secure { #see if secure is available. If it is, check that creds are cached. If not, user has to join.
  102.  
  103.         $secAvail = netsh wlan show networks | findstr /r "HSC_Secure"
  104.         if ( ! $secAvail ) {
  105.             Dirty-Quit("HSC_Secure is unavailabe. No other connection found. Connection via ethernet required")
  106.         }
  107.         else {
  108.             Write-Host "Attempting to connect to HSC_Secure..."
  109.             netsh wlan connect ssid=HSC_Secure name=HSC_Secure interface="Wireless Network Connection" | Out-Null
  110.             if (! $?) { Dirty-Quit("Connection to HSC_Secure failed due to incorrect or missing credentials. Please connect manually.") }
  111.             else {
  112.                 write-host "Pausing five seconds to allow connection to complete...."
  113.                 Start-Sleep -s 5
  114.                 return
  115.             }
  116.         }
  117.     }
  118.  
  119.  
  120.     function Remove-Guest {
  121.        
  122.         if ( Get-Networks -eq "HSC_Guest" ) { netsh wlan disconnect interface="Wireless Network Connection" | Out-Null }
  123.         $WLAN_Profiles = netsh wlan show profiles | findstr /r "HSC_Guest"
  124.         if ($WLAN_Profiles) { netsh wlan delete profile HSC_Guest | Out-Null }
  125.     }
  126.  
  127.  
  128.     #Checks to make sure PS is >=3 and PSWindowsUpdate is in the Modules
  129.  
  130.     function checkVer {
  131.         if ( ! (Test-Path C:\windows\System32\WindowsPowershell\v1.0\Modules\PSWindowsUpdate) -or ($PSVersionTable.PSVersion | select -expand Major) -lt 3 ) {
  132.             return $false
  133.         } else {
  134.             return $true
  135.         }
  136.     }
  137.  
  138.     #We need to set these variables before establishing the function, otherwise PS gets all pee-pee hearted
  139.     #Get Scheduled Tasks
  140.     $TaskSchedule = New-Object -com("Schedule.Service")
  141.     $TaskSchedule.connect("localhost")
  142.     try
  143.     {
  144.         $EnabledTasks = $TaskSchedule.getfolder("\apple").gettasks(0) | Format-Table name
  145.     }
  146.     catch {}
  147.  
  148.     $EnabledTasks += $TaskSchedule.getfolder("\").gettasks(0) | Format-Table name
  149.     $EnabledTasks = $EnabledTasks | Format-Table Name
  150.  
  151.     #Get Running Process
  152.     $RunningProcesses = Get-Process | Format-Table name
  153.    
  154.     #Kills processes that are running
  155.     function Kill-Process {
  156.         param($ProcessName)
  157.         $CheckProcess = $RunningProcesses | findstr /r "$ProcessName"
  158.         if ($CheckProcess) {  Stop-Process -processname "$ProcessName" -Force }
  159.         else { Write-Host "Process $ProcessName is not running" -ForegroundColor DarkYellow }
  160.     }
  161.  
  162.     function Disable-SchedTask {
  163.         param(
  164.             [string]$RootFolder,
  165.             [string]$TaskName
  166.         )
  167.         $TaskEnabled = $EnabledTasks | findstr /r $TaskName
  168.         if ($TaskEnabled) {
  169.             $WorkTask = $TaskSchedule.GetFolder("$RootFolder").GetTask("$TaskName")
  170.             $WorkTask.Enabled = $False }
  171.         else { Write-Host "Task $TaskName is not a scheduled task" -ForegroundColor DarkYellow }
  172.     }
  173.  
  174.     #Check for PS version and PSWindowsUpdate before continuing to load those
  175.  
  176.     $hasVer = checkVer
  177.  
  178.    
  179.     #
  180.     #
  181.     # End of function declarations. Runtime code starts
  182.     # here.
  183.     #
  184.     #
  185.     #
  186.  
  187.     #Set our variables
  188.     $userPath=$env:TEMP
  189.     $DateStr = Get-Date -format "MMM-dd-yyyy"
  190.  
  191.     #Find our connection
  192.     $connStatus = Get-Networks
  193.     if (! $connStatus) { Write-Host "No current connections found" }
  194.     else { Write-Host "Connected via $connStatus" }
  195.     switch ($connStatus) {
  196.         $false {
  197.             Check-Secure
  198.             Check-Time
  199.         }
  200.  
  201.         "Local Area Connection" {
  202.  
  203.             Check-Time
  204.         }
  205.  
  206.         "HSC_Secure" {
  207.             Check-Time
  208.         }
  209.  
  210.         "HSC_Guest" {
  211.             Write-Host "HSC_Guest cannot be used for testing purposes."
  212.             Remove-Guest
  213.             Check-Secure
  214.             Check-Time
  215.         }
  216.         "Unknown Network" {
  217.            Write-Host "We're connected to an unknown network, so we're just going to give a shot. No promises." -BackgroundColor Yellow -ForegroundColor White
  218.         }
  219.  
  220.      }
  221.    
  222.    
  223.     #All of this functionality relies on an updated version of PS (Management Framework 4)
  224.     #And a particular library that needs to be installed.
  225.     if ($hasVer)
  226.     {
  227.         Import-Module PSWindowsUpdate
  228.         write-host "Checking reboot status..."
  229.         Get-WURebootStatus #This function asks the user if they want to restart, so we don't have to.
  230.         Write-Host "Checking that Windows is activated..."
  231.         $isActivated = Check-Activation
  232.         if ( $isActivated -eq "Licensed" ) { Write-Host "Windows is activated." -ForegroundColor Green }
  233.         else {
  234.            Dirty-Quit("Windows in an unactivated state will interrupt the testing ")
  235.         }
  236.     }
  237.     else
  238.     {
  239.         Write-Host "INFO: Module PSWindowsUpdate is missing, or the PowerShell version installed does not support it." -ForegroundColor Black -BackgroundColor Yellow
  240.         Write-Host "INFO: Some (non-essential) functionality has been disabled." -ForegroundColor White -BackgroundColor Yellow
  241.     }
  242.  
  243.    #Stop the windows update service to prevent it from interrupting our test
  244.  
  245.     Write-Host "Stopping Windows Update services..."
  246.     Stop-Service wuauserv -force
  247.     Stop-Service bits -force
  248.     Stop-Service appidsvc -force
  249.     Stop-Service cryptsvc -force
  250.     Write-Host "Done." -ForegroundColor Green
  251.  
  252.     #Stop any update processes that may be running
  253.     Write-Host "Killing any software process that may interrupt our user's session"
  254.     Kill-Process("SoftwareUpdate")
  255.     Kill-Process("AdobeARM")
  256.     Kill-Process("FlashPlayerUpdateService")
  257.     Kill-Process("jusched")
  258.     Write-Host "Done." -ForegroundColor Green
  259.    
  260.     #Stop any Scheduled Services that may interrupt our session
  261.     Write-Host "Disabling all scheduled tasks that may interrupt our user's session"
  262.     Disable-SchedTask "\" "Adobe Flash Player Updater"
  263.     Disable-SchedTask "\Apple" "AppleSoftwareUpdate"
  264.     Write-Host "Done." -ForegroundColor Green
  265.  
  266.     #Create download object, and download
  267.     Write-Host "Grabbing NBME Secure Browser ($DateStr). This may take a while..."
  268.     $Client = New-Object System.Net.WebClient
  269.     $GetFile = "https://wbt.nbme.org/wbtexam/download/today/PCSecureBrowser-$(Get-Date -format "MMM-dd-yyyy").exe"
  270.     $ExecFile = "$userPath\PCSecureBrowser-$DateStr.exe"
  271.     try
  272.     {
  273.     $Client.DownloadFile($GetFile,$ExecFile)
  274.     }
  275.     catch
  276.     {
  277.         $count = 0
  278.         do {
  279.             $count++
  280.             Write-Host "Download command failed to complete! Retrying $count of 3" -BackgroundColor Red -ForegroundColor White
  281.             Start-Sleep -s 5
  282.             try
  283.             {
  284.             $Client.DownloadFile($GetFile,$ExecFile)
  285.             }
  286.             catch {}
  287.         } while ( (! $?) -and ($count -lt 3))
  288.         if ( $count -ge 3 ) {
  289.         Dirty-Quit("The download failed to complete. Check internet connectivity.")
  290.         }
  291.     }
  292.     Write-Host "Download command completed successfully." -ForegroundColor green
  293.     Write-Host "Verifying File..."
  294.  
  295.     if (Test-Path $ExecFile)
  296.     {
  297.         Write-Host "Success!" -ForegroundColor Green
  298.     }
  299.     else
  300.     {
  301.         Dirty-Quit("There was something wrong with the download. Try again, or download manually.")
  302.     }
  303.  
  304.     #Start secure exam, and wait for it to finish before continuing.
  305.     Write-Host "Starting Secure Exam..."
  306.     & $ExecFile | Out-Null
  307.     Write-Host "Secure Exam Finished."
  308.  
  309.     #Restart Windows Update services
  310.     Write-Host "Restarting Windows Update services..."
  311.     Start-Service wuauserv
  312.     Start-Service bits
  313.     Start-Service appidsvc
  314.     Start-Service cryptsvc
  315.     Write-Host "Done." -ForegroundColor Green
  316.  
  317.     #Clean up
  318.     Write-Host "Cleaning up..."
  319.     Remove-Item $ExecFile
  320.    
  321.     Write-Host "All tasks completed! We're done here." -ForegroundColor Green
  322.     Clean-Quit
Add Comment
Please, Sign In to add comment