Showing posts with label local security policy. Show all posts
Showing posts with label local security policy. Show all posts

Monday, February 18, 2013

Use vbscript to edit local security policy

Recently I found the need to automate the addition of a user to the "logon as a service" local security policy of a windows system.  I found a lot of post about "how do I" and no definitive (start TO finish) summations to accomplish such.  So here it is:


Const ForReading = 1
Const ForAppending = 8
Const ForWriting = 2
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")

'Grant logonasaservice right to the service user
strDomUser = "yourdomainuser"
strDom = "yourdomain"
'identifies the AD SID for the specified user
Set objAccount = objWMIService.Get("Win32_UserAccount.Name='" & strDomUser & "',Domain='" & strDom & "'")
'exports the user rights local policy
strComSec1 = "secedit /export /areas user_rights /cfg C:\temppath\~security.inf"
objShell.Run strComSec1, 0, True
'opens the unicode output to be parsed
Set strInpFile = objFSO.OpenTextFile("C:\temppath\~security.inf", ForReading, False, -1)
strInput = strInpFile.ReadAll
strInpFile.Close
objFSO.DeleteFile "D:\Scripts\Tcat\Service_Install\~security.inf"
'looks for the user SID - If the user had previously been given specific local policy rights you will have to refine this further.
If InStr(strInput, objAccount.SID) <= 0 Then
'build replacedment policy information - this is specific to "logon as a service" permissions - note the two values, one is a default nt services value, the other is the new SID
strData = "[Unicode]" & vbCrLf & "Unicode=yes" & vbCrLf & "[Version]" & vbCrLf & "signature=""$CHICAGO$""" & vbCrLf & "Revision=1" & vbCrLf & "[Privilege Rights]" & vbCrLf & "SeServiceLogonRight = *S-1-5-80-0,*" & objAccount.SID
Set strInpFile = objFSO.OpenTextFile("C:\temppath\~SecurityTemplate.inf", ForWriting, True, -1)
strInpFile.Write strData
strInpFile.Close
'edit the policy
strComSec2 = "secedit /configure /db C:\Windows\security\database\secedit.sdb /cfg ""C:\temppath\~SecurityTemplate.inf"" /areas user_rights /log seclog.loc"
objShell.Run strComSec2, 0, True
objFSO.DeleteFile "D:\Scripts\Tcat\Service_Install\~SecurityTemplate.inf"
End If