Image

Image

Search This Blog

Tuesday, January 18, 2011

Install Windows printers

' replacepr.vbs - Windows NT Logon Script. (c) 2008-2010 sorin@xxxxxxx Inc.
' VBScript - Silently remove ALL network printers, install new ones with default
' this script require 2 additional files: one defining the printers we need to
' install, one printer per line and a second file defining what default printer
' we use, depending on what IP range this computer belongs the format of this
' file is IP_Range, Default_Printer (IP_Range is defined as, ex: 10.0.IP_Range.9)
' -----------------------------------------------------------------------'

Dim printer, sServer, i, l, default
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNet = CreateObject("WScript.Network")
Set WshShell = CreateObject("WScript.Shell")
Set wmiLocator = CreateObject("WbemScripting.SWbemLocator")
Set wmiNameSpace = wmiLocator.ConnectServer(objNet.ComputerName, "root\default")
Set objRegistry = wmiNameSpace.Get("StdRegProv")
Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
strComputer = "."
'Define the server where printers reside
sServer = "\\sqlsrv"
'If the OS is win7 we need to install printers from a win 2008 server
Set objWMIService = GetObject("winmgmts:" &_
"{impersonationLevel=impersonate}!\\" & strComputer & _
"\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
if objOperatingSystem.Caption = "Microsoft Windows 7 " then sServer = "\\2k8srv"
'wscript.echo sServer
Next

' If this script alredy run once for this user, then EXIT
userprrf = WshShell.Environment("PROCESS")("UserProfile")
'wscript.Echo userprrf
If (objFSO.FileExists(userprrf & "\sctwashere.txt")) Then
Wscript.Quit
Else
blah = "let's have some fun"
End If

' Deletes RegistryKey with all subkeys in Network printers
sPath = "Printers\Connections"
lRC = DeleteRegEntry(HKEY_CURRENT_USER, sPath)
Function DeleteRegEntry(sHive, sEnumPath)
' Attempt to delete key. If it fails, start the subkey enumration process.
lRC = objRegistry.DeleteKey(sHive, sEnumPath)
' The deletion failed, start deleting subkeys.
If (lRC <> 0) Then
' Subkey Enumerator
On Error Resume Next
lRC = objRegistry.EnumKey(HKEY_CURRENT_USER, sEnumPath, sNames)
For Each sKeyName In sNames
If Err.Number <> 0 Then Exit For
lRC = DeleteRegEntry(sHive, sEnumPath & "\" & sKeyName)
Next
On Error Goto 0
' At this point we should have looped through all subkeys, trying to delete the key again.
lRC = objRegistry.DeleteKey(sHive, sEnumPath)
End If
End Function
'Now let's recreate the "root" Key we deleted before
objRegistry.CreateKey HKEY_CURRENT_USER,sPath

'Tell something to the user
'with createobject("wscript.shell")
' .popup "All Printers are now erased, Reinstalling...",5, "Printers Manager"
'end with

'Let's see in what ip range we are, so we can choose a default printer
Set objWMIService = GetObject( _
"winmgmts:\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery _
("Select IPAddress from Win32_NetworkAdapterConfiguration ")

For Each IPConfig in IPConfigSet
If Not IsNull(IPConfig.IPAddress) Then
For i=LBound(IPConfig.IPAddress) _
to UBound(IPConfig.IPAddress)
strArray=Split(IPConfig.IPAddress(i),".")
if ubound(strArray) > 2 Then
'WScript.Echo strArray(2)
if strArray(0) = 192 And strArray(1) = 168 Then
Exit For
End if
End If
Next
End If
Next
' Read the file containig the pair ip-range, default-printer
'(the ip range is the 3rd digit in the ip - 10.0.X.3 - gives X as range)
Set objFile = objFSO.OpenTextFile("defaultlist.txt", ForReading)
'WScript.Echo strArray(2)
Do Until objFile.AtEndOfStream
defaultArray = split(objFile.ReadLine,",")
if defaultArray(0) = strArray(2) Then
defaultprt=defaultArray(1)
'wscript.Echo defaultArray(1)
exit do
end if
Loop
objFile.Close

default = sServer & "\" & defaultArray(1)
'wscript.Echo default

'Now let's start installing the printers listed in plist.txt
Set objFile = objFSO.OpenTextFile("plist.txt", ForReading)

Do Until objFile.AtEndOfStream
printer = objFile.ReadLine
printer = sServer & "\" & printer
if printer = default then
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & printer & """ /u /q /Gw"
WshShell.Run strCmd,,true
strCmd = "rundll32 printui.dll,PrintUIEntry /y /n """ & printer & ""
else
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & printer & """ /u /q /Gw"
end if
WshShell.Run strCmd
Loop
objFile.Close


with createobject("wscript.shell")
.popup "All Printers Are Now ReInstalled",15, "Printers Management"
end with

'We're done, let's leave a trace in userprofile, so at next login this script will exit
Set objFile1 = objFSO.CreateTextFile(userprrf & "\sctwashere.txt")

Wscript.Quit

Saturday, January 15, 2011

Monitor windows logs

Thanks to Stefan Plattner (http://twitter.com/splattne)
Considering that Intel's Matrix Raid does not have a way to send emails
in case of a HDD failure, I've searched for a way of monitoring the
Windows system log and send a mail in case of an event. The monitoring
part can be solved with a simple vbs script (made by splattne), this
script being run as service by the "Non-Sucking Service Manager"
( http://iain.cx/src/nssm/ ).
You can define the events you want to be alerted on, in the vbs script
with the "PushEventToMonitor" call. The arguments are: event ID, event
log name, source, category, type, user, and a regular expression that
can be matched against the log message. We have an example in the vbs
script that matches the start / stop of the TELNET service, as well as
one that will match the startup of the script itself (which logs an
event out to the Application Log) and a real case for Intel MatrixRaid.
In order to install the service, run in a command prompt: "nssm install
SimpleEventLogMonitor" and in the following window choose
"%SystemRoot%\System32\cscript.exe" as Application and
"c:\Path\to\eventmonitor.vbs" as Option.
To uninstall run: "nssm remove SimpleEventLogMonitor confirm" (Warning:
you can uninstall any service with this command!)


vbs script starts here:


Option Explicit

' Main
Dim objShell, objWMIService, objEventSink, dictEventsToMonitor, eventToMonitor

' =====================( Configuration )=====================

' Set to 0 to disable event log reporting of bans / unbans
Const USE_EVENTLOG = 0
Const EVENTLOG_SOURCE = "SimpleEventMonitor"

' SMTP configuration
Const EMAIL_SENDER = "EventLogMonitor@xxxxxxxxxxxx.ca"
Const EMAIL_RECIPIENT = "sorin@xxxxxxxx.com"
Const EMAIL_SMTP_SERVER = "relais.xxxxxxxxxx.ca"
Const EMAIL_SMTP_PORT = 25
Const EMAIL_TIMEOUT = 20

Set dictEventsToMonitor = CreateObject("Scripting.Dictionary")

' Define events that should be monitored. Matches are based on exact matches of all non-NULL fields
' Order: event ID, event log name, source, category, type, user, and a regular expression
'PushEventToMonitor "100", "Application", EVENTLOG_SOURCE, NULL, NULL, NULL, NULL
'PushEventToMonitor "7036", "System", "Service Control Manager", NULL, NULL, NULL, "Telnet service.*(running|stopped).*state"

' Monitor my Intel service
PushEventToMonitor "7202", "System", " IAANTmon", NULL, "Warning", NULL, NULL

' ===================( End Configuration )===================


Set objShell = CreateObject("WScript.Shell")

' Create event sink to catchevents
Set objWMIService = GetObject("winmgmts:{(security)}!root/cimv2")
Set objEventSink = WScript.CreateObject("WbemScripting.SWbemSink", "eventSink_")
objWMIService.ExecNotificationQueryAsync objEventSink, "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent'"

' Loop sleeping for one week, logging an event each week to say we're still alive
While (True)
LogEvent 100, "INFORMATION", "Simple Event Log Monitor started"
WScript.Sleep(7 * 24 * 60 * 60 * 1000)
Wend

' Fires each time new events are generated
Sub eventSink_OnObjectReady(objEvent, objWbemAsyncContext)
Dim evt, field, boolAlert, regexpMessage

For Each evt In dictEventsToMonitor.Keys
boolAlert = True

For Each field In dictEventsToMonitor.Item(evt).Keys
If UCase(Field) = "MESSAGE" Then
Set regexpMessage = new Regexp
regexpMessage.Pattern = dictEventsToMonitor.Item(evt).Item(Field)
regexpMessage.IgnoreCase = True
If NOT regexpMessage.Test(objEvent.TargetInstance.Properties_(Field)) then boolAlert = False
Else
If UCase(objEvent.TargetInstance.Properties_(Field)) <> UCase(dictEventsToMonitor.Item(evt).Item(field)) Then boolAlert = False
End If
Next ' field

if boolAlert = True Then
SendMessage "Simple Event Log Monitor notification from " & objEvent.TargetInstance.ComputerName, _
"Event ID: " & objEvent.TargetInstance.EventCode & VbCrLf _
& "Date/Time: " & Mid(objEvent.TargetInstance.TimeGenerated, 5, 2) & "/" & Mid(objEvent.TargetInstance.TimeGenerated, 7, 2) & "/" & Mid(objEvent.TargetInstance.TimeGenerated, 1, 4) & " " & Mid(objEvent.TargetInstance.TimeGenerated, 9, 2) & ":" & Mid(objEvent.TargetInstance.TimeGenerated, 11, 2) & ":" & Mid(objEvent.TargetInstance.TimeGenerated, 13, 2) & VbCrLf _
& "Computer: " & objEvent.TargetInstance.ComputerName & vbCrLf _
& "Event Log: " & objEvent.TargetInstance.LogFile & vbCrLf _
& "Event Source: " & objEvent.TargetInstance.SourceName & vbCrLf _
& "Event Category: " & objEvent.TargetInstance.CategoryString & vbCrLf _
& "Event Type: " & objEvent.TargetInstance.Type & vbCrLf _
& "User Name: " & objEvent.TargetInstance.User & vbCrLf _
& "Message:" & vbCrLf & vbCrLF _
& objEvent.TargetInstance.Message
Exit Sub
End If

Next ' evt
End Sub

Sub LogEvent(ID, EventType, Message)
' Log an event to the Windows event log
If USE_EVENTLOG Then objShell.Exec "EVENTCREATE /L APPLICATION /SO " & EVENTLOG_SOURCE & " /ID " & ID & " /T " & EventType & " /D """ & Message & """"
End Sub

Sub SendMessage(strSubject, strBody)
Dim objCDOMessage
Set objCDOMessage = CreateObject("CDO.Message")

objCDOMessage.From = EMAIL_SENDER
objCDOMessage.To = EMAIL_RECIPIENT
objCDOMessage.Subject = strSubject
objCDOMessage.Textbody = strBody
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = EMAIL_SMTP_SERVER
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = EMAIL_SMTP_PORT
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = EMAIL_TIMEOUT
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objCDOMessage.Configuration.Fields.Update
objCDOMessage.send
End Sub

Sub PushEventToMonitor(strID, strLog, strSource, strCategory, strType, strUser, strMessagePattern)
Dim x

x = dictEventsToMonitor.Count
Set dictEventsToMonitor.Item(x) = CreateObject("Scripting.Dictionary")
If NOT IsNull(strID) Then dictEventsToMonitor.Item(x).Add "EventCode", strID
If NOT IsNull(strLog) Then dictEventsToMonitor.Item(x).Add "LogFile", strLog
If NOT IsNull(strSource) Then dictEventsToMonitor.Item(x).Add "SourceName", strSource
If NOT IsNull(strCategory) Then dictEventsToMonitor.Item(x).Add "CategoryString", strCategory
If NOT IsNull(strType) Then dictEventsToMonitor.Item(x).Add "Type", strType
If NOT IsNull(strType) Then dictEventsToMonitor.Item(x).Add "User", strUser
If NOT IsNull(strMessagePattern) Then dictEventsToMonitor.Item(x).Add "Message", strMessagePattern
End Sub

Blog Archive