Partager via


Runonce.vbs

By The Scripting Guys, Microsoft Corporation

This script configures Windows Firewall and cleans up registry entries set by install.vbs or install-local.vbs. It is automatically launched locally on the network host after install.vbs or install-local.vbs completes its work, and performs the following tasks:

  • Runs after machine reboots for first time, launched by RunOnce registry entry.

  • Configures Windows Firewall to allow certain programs and open certain ports. You must edit these settings to reflect the configuration of your network.

  • Enables remote administration on Windows Firewall so that remote scripts and administrative tools can again run against this host.

  • Resets AutoAdmin and RunOnce registry entries.

  • Logs results to text file, computername-sp2-clnuplog.txt and, in Scenario 1, copies the file back to admin workstation.

  • Again forces a reboot.

Further explanation of Scenarios 1 and 2 and the role of each script is contained in the introduction to these scripts at:

https://www.microsoft.com/technet/scriptcenter/solutions/appcompat/default.mspx

Runonce.vbs corresponds and adds functionality to runonce.cmd, one of the scripts that ships with Application Compatibility Testing and Mitigation Guide for Windows XP Service Pack 2 and which are documented in the Appendix. You can download a Windows Installer (.msi) file that installs the Guide and its associated scripts from:

https://www.microsoft.com/downloads/details.aspx?FamilyId=9300BECF-2DEE-4772-ADD9-AD0EAF89C4A7&displaylang=en

To use the script, copy the code, paste it into Notepad, and then save the script as runonce.vbs. The script is designed to be run automatically as part of the process initiated by scenario1.vbs or scenario2.vbs.

Script Code

'******************************************************************************
'runonce.vbs
'Author: Peter Costantini, the Microsoft Scripting Guys
'Date: 9/1/04
'Must be deployed to a client by scenario1.vbs, or present on the local
'computer for scenario2.vbs.
'Runs on client when it reboots because specified in RunOnce reg entry.
'Assumes that scenario1.vbs, install.vbs and the Windows XP Service Pack 2
'setup program have already run.
'1. Configures Windows Firewall to allow certain programs and open certain
'ports.
'2. Enables remote administration on Windows Firewall.
'3. Removes the AutoAdmin and RunOnce registry settings that were necessary
'   for this script to run.
'4. Forces a reboot of the local machine so that the changes take effect.
'******************************************************************************

On Error Resume Next

'Initialize global constants and variables.
Const FOR_APPENDING = 8
g_strLocalFolder = "c:\temp-ac"
'Change name of computer to actual administrative workstation or local folder
'to which log should be copied.
g_strRemoteFolder = "\\<adminwkstn>\c$\scripts-ac"
'If running this script with scenario2.vbs, change to a local folder, e.g.:
'g_strRemoteFolder = "c:\temp-ac\logs"

'Get computer name.
g_strComputer = GetComputerName
g_strLogFile = g_strComputer & "-sp2-clnuplog.txt"

'Create log file.
Set g_objFSO = CreateObject("Scripting.FileSystemObject")
Set g_objTextStream = g_objFSO.OpenTextFile(g_strLogFile, FOR_APPENDING, True)
g_objTextStream.WriteLine "Windows XP Service Pack 2 " & _
 "Cleanup and Firewall Log: Phase 2"
g_objTextStream.WriteLine Now
g_objTextStream.WriteLine g_strComputer
g_objTextStream.WriteLine String(Len(g_strComputer), "-")

'Handle logic of calling functions and sub-routines.
ConfigWinFire
blnCleanUpReg = CleanUpReg
If blnCleanUpReg = False Then
  CopyLog
  WScript.Quit
End If
Reboot

'******************************************************************************

Function GetComputerName

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\." _
 &"\root\cimv2")
Set colSystems = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem")
For Each objSytem In colSystems
  GetComputerName = objSytem.Name
Next

End Function

'******************************************************************************

Sub ConfigWinFire

Const NET_FW_IP_PROTOCOL_TCP = 6
Const NET_FW_IP_PROTOCOL_UDP = 17
'First dimension of arrNewPorts must equal # of ports to be added minus 1.
Dim arrNewPorts(3,2)
'First dimension of arrNewApps must equal # of apps to be allowed minus 1.
Dim arrNewApps(2,1)

'Edit this list to add or remove ports on the exceptions list.
'Scope, and Enabled are optional properties not used here.
'Default for Scope is NET_FW_SCOPE_ALL. Default for Enabled is True.

arrNewPorts(0,0) = "FPS" 'Name
arrNewPorts(0,1) = 137 'Port
arrNewPorts(0,2) = NET_FW_IP_PROTOCOL_UDP 'Protocol

arrNewPorts(1,0) = "FPS1"
arrNewPorts(1,1) = 138
arrNewPorts(1,2) = NET_FW_IP_PROTOCOL_UDP

arrNewPorts(2,0) = "FPS2"
arrNewPorts(2,1) = 139
arrNewPorts(2,2) = NET_FW_IP_PROTOCOL_TCP

arrNewPorts(3,0) = "FPS3"
arrNewPorts(3,1) = 445
arrNewPorts(3,2) = NET_FW_IP_PROTOCOL_TCP

'Edit this list to add or remove programs on the exceptions list.
'Scope, and Enabled are optional properties not used here.
'Default for Scope is NET_FW_SCOPE_ALL. Default for Enabled is True.

arrNewApps(0,0) = "NsLookup" 'Name
arrNewApps(0,1) = "%windir%\system32\nslookup.exe" 'ProcessImageFileName
'Must be a fully qualified path, but can contain environment variables.

arrNewApps(1,0) = "Notepad"
arrNewApps(1,1) = "%windir%\system32\notepad.exe"

arrNewApps(2,0) = "Calculator"
arrNewApps(2,1) = "%windir%\system32\calc.exe"

'Create the firewall manager object.
Set objFwMgr = CreateObject("HNetCfg.FwMgr")
If Err <> 0 Then
  g_objTextStream.WriteLine "Unable to connect to Windows Firewall."
  Exit Sub
End If
'Get the current profile for the local firewall policy.
Set objProfile = objFwMgr.LocalPolicy.CurrentProfile
Set colOpenPorts = objProfile.GloballyOpenPorts
Set colAuthorizedApps = objProfile.AuthorizedApplications

g_objTextStream.WriteLine VbCrLf & "Windows Firewall"
g_objTextStream.WriteLine VbCrLf & "Port Settings:"
g_objTextStream.WriteLine VbCrLf & "New open ports added:"
For i = 0 To UBound(arrNewPorts)
'Create an FWOpenPort object
  Set objOpenPort = CreateObject("HNetCfg.FWOpenPort")
  objOpenPort.Name = arrNewPorts(i, 0)
  objOpenPort.Port = arrNewPorts(i, 1)
  objOpenPort.Protocol = arrNewPorts(i, 2)
  colOpenPorts.Add objOpenPort
  If Err = 0 Then
    g_objTextStream.WriteLine "Name: " & objOpenPort.Name
    g_objTextStream.WriteLine "  Protocol: " & objOpenPort.Protocol
    g_objTextStream.WriteLine "  Port Number: " & objOpenPort.Port
  Else
    g_objTextStream.WriteLine "Unable to add port: " & arrNewPorts(i, 0)
    g_objTextStream.WriteLine "  Error Number:" & Err.Number
    g_objTextStream.WriteLine "  Source:" & Err.Source
    g_objTextStream.WriteLine "  Description:" & Err.Description
  End If
  Err.Clear
Next

g_objTextStream.WriteLine VbCrLf & "All open ports:"
For Each objPort In colOpenPorts
  g_objTextStream.WriteLine "Name: " & objPort.Name
  g_objTextStream.WriteLine "  Protocol: " & objPort.Protocol
  g_objTextStream.WriteLine "  Port Number: " & objPort.Port
  g_objTextStream.WriteLine "  Scope: " & objPort.Scope
  g_objTextStream.WriteLine "  Enabled: " & objPort.Enabled
Next

g_objTextStream.WriteLine VbCrLf & "Application Settings:"
g_objTextStream.WriteLine VbCrLf & "New authorized applications added:"
For i = 0 To UBound(arrNewPorts)
'Create an FwAuthorizedApplication object
  Set objAuthorizedApp = CreateObject("HNetCfg.FwAuthorizedApplication")
  objAuthorizedApp.Name = arrNewApps(i,0)
  objAuthorizedApp.ProcessImageFileName = arrNewApps(i, 1)
  colAuthorizedApps.Add objAuthorizedApp
  If Err = 0 Then
    g_objTextStream.WriteLine "Name: " & objAuthorizedApp.Name
    g_objTextStream.WriteLine "  Process Image File: " & _
     objAuthorizedApp.ProcessImageFileName
  Else
    g_objTextStream.WriteLine "Unable to add application: " & arrNewApps(i,0)
    g_objTextStream.WriteLine "  Error Number:" & Err.Number
    g_objTextStream.WriteLine "  Source:" & Err.Source
    g_objTextStream.WriteLine "  Description:" & Err.Description
  End If
  Err.Clear
Next

g_objTextStream.WriteLine VbCrLf & "All authorized applications:"
For Each objApp In colAuthorizedApps
  g_objTextStream.WriteLine "Name: " & objApp.Name
  g_objTextStream.WriteLine "  Protocol: " & objApp.ProcessImageFileName
  g_objTextStream.WriteLine "  Scope: " & objPort.Scope
  g_objTextStream.WriteLine "  Enabled: " & objPort.Enabled
Next

'Get remote admin settings.
Set objRemoteAdminSettings = objProfile.RemoteAdminSettings
'If remote administration not enabled, enable it.
If objRemoteAdminSettings.Enabled = False Then
  objRemoteAdminSettings.Enabled = True
  g_objTextStream.WriteLine VbCrLf & "Enabled Remote Administration."
Else
  g_objTextStream.WriteLine VbCrLf & "Remote Administration already enabled."
End If
g_objTextStream.WriteLine "Remote Administration Settings:"
g_objTextStream.WriteLine "Enabled: " & objRemoteAdminSettings.Enabled
If objRemoteAdminSettings.Scope = 0 Then
  strScope = "All" 'Default
ElseIf objRemoteAdminSettings.Scope = 1 Then
  strScope = "Local Subnet"
Else
  strScope = "UNKNOWN"
End If
g_objTextStream.WriteLine "Scope: " & strScope

End Sub

'******************************************************************************

Function CleanUpReg

Const HKEY_LOCAL_MACHINE = &H80000002
strKeyPath1 = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
strKeyPath2 = "SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
strRunoncePath = g_strLocalFolder & "\runonce.vbs"
'Edit these variables to reset defaults to what they were previously.
strDefaultUserName = ""
strDefaultPassword = ""
strDefaultDomainName = ""
intAutoAdminLogon = 0
strRunOnceEntry = "MyScript"

Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
 strComputer & "\root\default:StdRegProv")

'Edit strDefaultUserName if default user should not be set to empty string.
intRet1 = objReg.SetStringValue(HKEY_LOCAL_MACHINE, strKeyPath1, _
 "DefaultUserName", strDefaultUserName)
If intRet1 <> 0 Then
  g_objTextStream.WriteLine "Error: DefaultUserName not configured."
End If

'Edit strDefaultPassword if default password should not be set to empty string.
intRet2 = objReg.SetStringValue(HKEY_LOCAL_MACHINE, strKeyPath1, _
 "DefaultPassword", strDefaultPassword)
If intRet2 <> 0 Then
  g_objTextStream.WriteLine "Error: DefaultPassword not configured."
End If

'Uncomment these lines and edit strDefaultDomainName if default domain
'for the username needs to be reset.
'intRet3 = objReg.SetStringValue(HKEY_LOCAL_MACHINE, strKeyPath1, _
' "DefaultDomainName", strDefaultDomainName)
'If intRet3 <> 0 Then
'  g_objTextStream.WriteLine "Error: DefaultDomainName not configured."
'End If

'Turn off AutoAdminLogon
intRet4 = objReg.SetStringValue(HKEY_LOCAL_MACHINE, strKeyPath1, _
 "AutoAdminLogon", intAutoAdminLogon)
If intRet4 <> 0 Then
  g_objTextStream.WriteLine "Error: AutoAdminLogon not configured."
End If

'Delete MyScript entry, which ran this script once, from RunOnce subkey.
intRet5 = objReg.DeleteValue(HKEY_LOCAL_MACHINE, strKeyPath2, _
 strRunOnceEntry)
If intRet5 <> 0 Then
  g_objTextStream.WriteLine "Error: MyScript RunOnce entry not configured."
End If

'Check that all registry write operations succeeded.
If (intRet1 + intRet2 + intRet3 + intRet4 + intRet5) = 0 Then
  g_objTextStream.WriteLine "AutoAdminLogon and RunOnce values reset to " & _
   "empty or deleted."
  CleanUpReg = True
Else
  g_objTextStream.WriteLine "Error: AutoAdminLogon and RunOnce could not " & _
   "be fully reset or deleted."
  CleanUpReg = False
End If

End Function

'******************************************************************************

Sub Reboot

Const FORCED_REBOOT = 6

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate," & _
 "(Shutdown)}")
Set colOSes = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem")
g_objTextStream.WriteLine "Attempting to reboot ..."
For Each objOS In colOSes 'only one
'  intReturn = objOS.Win32Shutdown(FORCED_REBOOT)
  If intReturn <> 0 Then
    Set g_objTextStream = g_objFSO.OpenTextFile(g_strLogFile, FOR_APPENDING, True)
    g_objTextStream.WriteLine Now
    g_objTextStream.WriteLine "Error: Unable to reboot." & VbCrLf & _
     "Return code: " & intReturn
    CopyLog
  End If
Next

End Sub

'******************************************************************************

Sub CopyLog

'Close text file.
g_objTextStream.WriteLine "Closing log and attempting to copy log to " & _
 "administrative workstation."
g_objTextStream.WriteLine
g_objTextStream.WriteLine String(80, "-")
g_objTextStream.WriteLine
g_objTextStream.Close

'If remote folder does not exist, create it.
If Not g_objFSO.FolderExists(g_strRemoteFolder) Then
  g_objFSO.CreateFolder(g_strRemoteFolder)
  If Err <> 0 Then
    Err.Clear
    Exit Sub
  End If
End If
'Copy log.
g_objFSO.CopyFile g_strLogFile, g_strRemoteFolder & "\"

End Sub

For online peer support, join The Official Scripting Guys Forum! To provide feedback or report bugs in sample scripts, please start a new discussion on the Discussions tab for this script.

Disclaimer

This sample script is not supported under any Microsoft standard support program or service. The sample script is provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.