Pub0030.htm

Run as Admin Code - Service Manipulation Scripts

Paz Itzhaki-Weinberger, 17-May-2013

 

paz

 

Dear Friends & Colleagues,

 

During my work I encountered a problem and wanted to share with everyone the solution.

 

The issue was a need to run a program as an administrator on a Windows system running with a standard user – not only was that the problem, but there was a need to run this automatically to all the users in the domain with a batch file, and to make sure no one is prompted with a password screen (the run as command is limited and does not allow input of a password). Actually the issue was a bit more complex and demanded that a service will be run as an administrator while the machine is operating with the standard user….

 

The problem was tough, yet I have a swift solution I’m sure you will all admire.

 

Enclosed see an example of both a script (please save as .vbs file, to be run with cscript) and a batch file (please save as .bat) to show how to use the sc command – obviously you need to run the batch file using the script – so you enter the batch into the WSNAME_COMMANDLINE and the administrator user and password into USER & PASS accordingly, and then run the code in a command like “cscript example.bat” and TA-DA, the deed is done!

 

Script Code Example

Option Explicit

 

Const USER                                          = "enter domain\username here"

Const PASS                                          = "enter password here"

Const WSNAME_COMMANDLINE          = "enter command line to run here"

 

Dim fso                         : Set fso = CreateObject("Scripting.FileSystemObject")

Dim WSHShell              : Set WshShell = CreateObject("WScript.Shell")

Dim WshNetwork           : Set WshNetwork = CreateObject("WScript.Network")

Dim oDic                       : Set oDic = CreateObject("Scripting.Dictionary")

Dim objArgs                  : Set objArgs = WScript.Arguments

Dim oProcessEnv          : Set oProcessEnv = WshShell.Environment("PROCESS")

 

Dim sPathToRunAs, iReturnCode

 

sPathToRunAs = oProcessEnv("SystemRoot")&"\System32\runas.exe"

''msgbox sPathtorunas

 

if Not fso.FileExists(sPathToRunAs) Then : WScript.Quit(1) 'Can't find RunAs

 

'''msgbox "runas /user:" & USER & " " & CHR(34) & WSNAME_COMMANDLINE & CHR(34)

iReturnCode=WshShell.Run("runas /user:" & USER & " " & CHR(34) & WSNAME_COMMANDLINE & CHR(34), 2, FALSE)

 

Wscript.Sleep 40                                               ' Time for window to open.

WshShell.AppActivate(sPathToRunAs)                ' Activate the Window

Wscript.Sleep 3

WSHShell.SendKeys PASS & "~"                      ' Send the password

Wscript.Sleep 3

 

''msgbox "done"

 

Batch File Example

sc config servicename obj= "domain\username" password= "password"

 

Good Luck,

 

Paz.