Jump to content

Windows Services UDF


GEOSoft
 Share

Recommended Posts

New function _Service_Change()

#cs*****************************************************************************

@error can be set to one of the following values :

-1      Service not found
0       Success
1       Not Supported
2       Access Denied
3       Dependent Services Running
4       Invalid Service Control
5       Service Cannot Accept Control
6       Service Not Active
7       Service Request Timeout
8       Unknown Failure
9       Path Not Found
10      Service Already Running
11      Service Database Locked
12      Service Dependency Deleted
13      Service Dependency Failure
14      Service Disabled
15      Service Logon Failure
16      Service Marked For Deletion
17      Service No Thread
18      Status Circular Dependency
19      Status Duplicate Name
20      Status Invalid Name
21      Status Invalid Parameter
22      Status Invalid Service Account
23      Status Service Exists
24      Service Already Paused

#ce*****************************************************************************

; $nServiceType
Global Const $KERNEL_DRIVER = 0x1
Global Const $FILE_SYSTEM_DRIVER = 0x2
Global Const $ADAPTER = 0x4
Global Const $RECOGNIZED_DRIVER = 0x8
Global Const $OWN_PROCESS = 0x10
Global Const $SHARE_PROCESS = 0x20
Global Const $INTERACTIVE_PROCESS = 0x100

; $nErrorType
Global Const $NOT_NOTIFIED = 0
Global Const $USER_NOTIFIED = 1
Global Const $SYSTEM_RESTARTED = 2
Global Const $SYSTEM_STARTS = 3

Global $error = -1

;===============================================================================
; Name:             _Service_Change()
; Description:      Modifies a service on a computer
; Parameters:       $sServiceName - name of the service to modify
;                   $sDisplayName - [optional] specify Default keyword if you are not changing the display name
;                   $sBinaryPath - [optional] specify Default keyword if you are not changing the path
;                   $sDescription - [optional] specify Default keyword if you are not changing the description
;                   $nServiceType - [optional] specify Default keyword if you are not changing
;                   $nErrorType - [optional] specify Default keyword if you are not changing
;                   $nStartType - [optional] specify Default keyword if you are not changing
;                   $sDesktopInteract - [optional] specify Default keyword if you are not changing
;                   $sServiceUser - [optional] specify Default keyword if you are not changing
;                   $sPassword - [optional] specify Default keyword if you are not changing the password
;                   $sLoadOrderGroup - [optional] specify Default keyword if you are not changing the load ordering group
;                   $sLoadOrderGroupDependencies - [optional] specify Default keyword if you are not changing
;                   $sDependencies - [optional] specify Default keyword if you are not changing
;                   $Computer - [optional] name of the target computer
;                               the local computer is default
; Requirements:     WMI capable operating system and administrator rights on the computer
; Return Values:    On Success - 1
;                   On Failure - 0
;                               @error - See table on top of this file for possible values
; Author(s):        engine
; Modification(s):
; Note(s):          See the _Service_Create() function for a more detailed description of each parameter
;                   You can't change the name of the service with this function
; Example(s):
;===============================================================================

Func _Service_Change( _
        $sServiceName, _
        $sDisplayName = Default, _
        $sBinaryPath = Default, _
        $sDescription = Default, _
        $nServiceType = Default, _
        $nErrorType = Default, _
        $nStartType = Default, _
        $sDesktopInteract = Default, _
        $sServiceUser = Default, _
        $sPassword = Default, _
        $sLoadOrderGroup = Default, _
        $sLoadOrderGroupDependencies = Default, _
        $sDependencies = Default, _
        $Computer = @ComputerName _
    )
    Local $Service = ObjGet("winmgmts:" & "{ImpersonationLevel=impersonate}!\\" & $Computer & "\root\cimv2")
    Local $sItems = $Service.ExecQuery ("Select * from Win32_Service where name like '"& $sServiceName &"'")
    For $objService In $sItems
        If ( $objService.StartName = "LocalSystem" And $sServiceUser = "NT AUTHORITY\NetworkService" ) Or _
        ( $objService.StartName = "NT AUTHORITY\NetworkService" And $sServiceUser = "LocalSystem" ) Then $sPassword = ""
        Local $error = $objService.Change( _
            $sDisplayName, _
            $sBinaryPath, _
            $nServiceType, _
            $nErrorType, _
            $nStartType, _
            $sDesktopInteract, _
            $sServiceUser, _
            $sPassword, _
            $sLoadOrderGroup, _
            $sLoadOrderGroupDependencies, _
            $sDependencies _
        )
        If $sDescription <> Default Then
            RegWrite("\\" & $Computer & "\HKLM\SYSTEM\CurrentControlSet\Services\" & $sServiceName, "Description", "REG_SZ", $sDescription)
        EndIf
        If $error = 0 Then Return 1
    Next
    Return SetError($error, 0, 0)
EndFunc   ;<==> _Service_Change()
Edited by engine

My contributions:Local account UDF Registry UDFs DriverSigning UDF Windows Services UDF [url="http://www.autoitscript.com/forum/index.php?showtopic=81880"][/url]

Link to comment
Share on other sites

  • Replies 100
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

_Service_Create() function revised:

#cs*****************************************************************************
@error can be set to one of the following values :

-1      Service not found
0       Success
1       Not Supported
2       Access Denied
3       Dependent Services Running
4       Invalid Service Control
5       Service Cannot Accept Control
6       Service Not Active
7       Service Request Timeout
8       Unknown Failure
9       Path Not Found
10      Service Already Running
11      Service Database Locked
12      Service Dependency Deleted
13      Service Dependency Failure
14      Service Disabled
15      Service Logon Failure
16      Service Marked For Deletion
17      Service No Thread
18      Status Circular Dependency
19      Status Duplicate Name
20      Status Invalid Name
21      Status Invalid Parameter
22      Status Invalid Service Account
23      Status Service Exists
24      Service Already Paused

#ce*****************************************************************************

; $nServiceType
Global Const $KERNEL_DRIVER = 0x1
Global Const $FILE_SYSTEM_DRIVER = 0x2
Global Const $ADAPTER = 0x4
Global Const $RECOGNIZED_DRIVER = 0x8
Global Const $OWN_PROCESS = 0x10
Global Const $SHARE_PROCESS = 0x20
Global Const $INTERACTIVE_PROCESS = 0x100

; $nErrorType
Global Const $NOT_NOTIFIED = 0
Global Const $USER_NOTIFIED = 1
Global Const $SYSTEM_RESTARTED = 2
Global Const $SYSTEM_STARTS = 3

Global $error = -1

;===============================================================================
; Name:             _Service_Create()
; Description:      Creates a service on a computer
; Parameters:       $sServiceName - name of the service to create
;                   $sDisplayName - display name of the service
;                   $sBinaryPath - fully qualified path to the service binary file
;                                   the path can also include arguments for an auto-start service
;                   $sDescription - [optional] description of the service
;                                   default is no description
;                   $nServiceType - [optional] default is $OWN_PROCESS
;                   $nErrorType - [optional] default is $NOT_NOTIFIED
;                   $nStartType - [optional] Possible options are "Boot", "System", "Automatic", "Manual" and "Disabled"
;                               default is "Automatic"
;                   $sDesktopInteract - [optional] Possible options are True and False
;                                       default is False
;                                       specify True only if the service will run on the LocalSystem account
;                                       otherwise the function will fail
;                   $sServiceUser - [optional] name of the account under which the service should run
;                                   default is "LocalSystem"
;                   $sPassword - [optional] password to the account name specified by $sServiceUser
;                               default is no password
;                               specify an empty string if the account has no password or if the service 
;                               runs in the LocalService, NetworkService, or LocalSystem account
;                   $sLoadOrderGroup - [optional] names the load ordering group of which this service is a member
;                                       default is no group
;                   $sLoadOrderGroupDependencies - [optional] array of load-ordering groups that must start before this service
;                                                   default is no dependencies
;                                                   group names must be prefixed by a "+" character to differentiate them from a service name
;                                                   because services and service groups share the same namespace
;                   $sDependencies - [optional] array that contains names of services that must start before this service starts
;                                   default is no dependencies
;                   $Computer - [optional] name of the target computer
;                               the local computer is default
; Requirements:     WMI capable operating system and administrator rights on the computer
; Return Values:    On Success - 1
;                   On Failure - 0
;                               @error - See table on top of this file for possible values
; Author(s):        engine
; Modification(s):  Total rewrite of this function by engine June 11, 2008
; Note(s):          To use default settings you must specify the Default keyword instead of
;                   an empty string "" for all the optional parameters except the $Computer parameter
;                   otherwise the function will fail
; Example(s):   
;===============================================================================

Func _Service_Create( _
        $sServiceName, _
        $sDisplayName, _
        $sBinaryPath, _
        $sDescription = Default, _
        $nServiceType = Default, _
        $nErrorType = Default, _
        $nStartType = Default, _
        $sDesktopInteract = Default, _
        $sServiceUser = Default, _
        $sPassword = Default, _
        $sLoadOrderGroup = Default, _
        $sLoadOrderGroupDependencies = Default, _
        $sDependencies = Default, _
        $Computer = @ComputerName _
    )
    Local $Service = ObjGet("winmgmts:" & "{ImpersonationLevel=impersonate}!\\" & $Computer & "\root\cimv2")
    Local $objService = $Service.Get("Win32_Service")
    Local $error = $objService.Create( _
        $sServiceName, _
        $sDisplayName, _
        $sBinaryPath, _
        $nServiceType, _
        $nErrorType, _
        $nStartType, _
        $sDesktopInteract, _
        $sServiceUser, _
        $sPassword, _
        $sLoadOrderGroup, _
        $sLoadOrderGroupDependencies, _
        $sDependencies _
    )
    If $error = 0 Then
        If $sDescription <> Default Then
            RegWrite("\\" & $Computer & "\HKLM\SYSTEM\CurrentControlSet\Services\" & $sServiceName, "Description", "REG_SZ", $sDescription)
        EndIf
        Return 1
    EndIf
    Return SetError($error, 0, 0)
EndFunc   ;<==> _Service_Create()
Edited by engine

My contributions:Local account UDF Registry UDFs DriverSigning UDF Windows Services UDF [url="http://www.autoitscript.com/forum/index.php?showtopic=81880"][/url]

Link to comment
Share on other sites

I'm going to be looking at these but from first glance I say there are too many params being used. As I pointed out before, There are more functions coming and I would rather use more functions than more parameters in each one. That is one of the reasons that I am eliminating a couple of the existing functions as written.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

I keep getting the following errors when I do a syntax check which are preventing me from using the UDF:

Services.au3(78,37) : WARNING: $SC_MANAGER_ALL_ACCESS: possibly used before declaration.

Services.au3(87,37) : WARNING: $SERVICE_INTERROGATE: possibly used before declaration.

Services.au3(78,37) : ERROR: $SC_MANAGER_ALL_ACCESS: undeclared global variable.

I'm using AutoIt 3.2.12.0 Is there an #include file I'm supposed to have?

Link to comment
Share on other sites

I keep getting the following errors when I do a syntax check which are preventing me from using the UDF:

Services.au3(78,37) : WARNING: $SC_MANAGER_ALL_ACCESS: possibly used before declaration.

Services.au3(87,37) : WARNING: $SERVICE_INTERROGATE: possibly used before declaration.

Services.au3(78,37) : ERROR: $SC_MANAGER_ALL_ACCESS: undeclared global variable.

I'm using AutoIt 3.2.12.0 Is there an #include file I'm supposed to have?

That is comming from _Service_Create(). I won't be doing any thing with this UDF until tomorrow. I just discovered that problem myself 2 days ago. I know what the problem is but it's one of the functions that I want to do a full re-write on. I'll probably update late tomorrow and I'll post here when I do.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

I keep getting the following errors when I do a syntax check which are preventing me from using the UDF:

Services.au3(78,37) : WARNING: $SC_MANAGER_ALL_ACCESS: possibly used before declaration.

Services.au3(87,37) : WARNING: $SERVICE_INTERROGATE: possibly used before declaration.

Services.au3(78,37) : ERROR: $SC_MANAGER_ALL_ACCESS: undeclared global variable.

I'm using AutoIt 3.2.12.0 Is there an #include file I'm supposed to have?

Hi.

You must open the file and declare those constants in the beginning of the function.

Local Const $SC_MANAGER_ALL_ACCESS = 0xF003F

Local Const $SERVICE_INTERROGATE = 0x0080

Taken from here -> http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx

Write that after:

Local $lError = -1

It should work.

My contributions:Local account UDF Registry UDFs DriverSigning UDF Windows Services UDF [url="http://www.autoitscript.com/forum/index.php?showtopic=81880"][/url]

Link to comment
Share on other sites

Hi.

You must open the file and declare those constants in the beginning of the function.

Local Const $SC_MANAGER_ALL_ACCESS = 0xF003F

Local Const $SERVICE_INTERROGATE = 0x0080

Taken from here -> http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx

Write that after:

Local $lError = -1

It should work.

That only solves part of the problem engine. There is a far more serious issue with that function. I'll be looking at it tomorrow.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

Might want to look at expanding the _Service_GetDetails() function to include Dependencies while you're at it GEOSoft. I know you can get them using SC CONFIG but I'm not sure with winmgmts.

_Service_EnumDepends()

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

Does anyone have an implementation of QueryServiceLockStatus?

I've been beating my head against this one for quite a while, but can't seem to get the parameters correct. :)

I'm trying to wait until the SCM is not locked.

Thanks!

Bill

Link to comment
Share on other sites

Does anyone have an implementation of QueryServiceLockStatus?

I've been beating my head against this one for quite a while, but can't seem to get the parameters correct. :)

I'm trying to wait until the SCM is not locked.

Thanks!

Bill

Did you attempt to use _Service_GetState()?

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

Did you attempt to use _Service_GetState()?

Thanks, but the point in the boot process where I intended to run the program is before the winmgmt service starts, so WMI is not functional at that time.

I currently have a C++ program that does the check, but I was hoping to be able to do it all in AutoIt.

Hmm, just checked MSDN, as of Vista, QueryServiceLockStatus is no longer supported.

Thanks

Bill

Edited by foggw
Link to comment
Share on other sites

"Where name like" in code doesn't work on Win 2000, I have to use "Where name ="

Thanks.

I have a work-around for that. I'll change it in the next few days and upload the changes. Alternately I'll just change "name like" to "name =" since I don't think it will effect anything anyway.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

A suggestion for improvement:

Remove:

_Service_GetFilePath()

_Service_GetPid()

_Service_GetStartMode()

_Service_GetState()

_Service_GetDescription

Improve:

_Service_GetDetails(), add a 3rd optional parameter, 1-17 - same as in returning array - where you just return that specific value.

Link to comment
Share on other sites

A suggestion for improvement:

Remove:

_Service_GetFilePath()

_Service_GetPid()

_Service_GetStartMode()

_Service_GetState()

_Service_GetDescription

Improve:

_Service_GetDetails(), add a 3rd optional parameter, 1-17 - same as in returning array - where you just return that specific value.

You mean add a flag?

I totally agree with you.

My contributions:Local account UDF Registry UDFs DriverSigning UDF Windows Services UDF [url="http://www.autoitscript.com/forum/index.php?showtopic=81880"][/url]

Link to comment
Share on other sites

A suggestion for improvement:

Remove:

_Service_GetFilePath()

_Service_GetPid()

_Service_GetStartMode()

_Service_GetState()

_Service_GetDescription

Improve:

_Service_GetDetails(), add a 3rd optional parameter, 1-17 - same as in returning array - where you just return that specific value.

It may happen that way and it may not. Right now there is a good chance that _Service_GetDetails() will be removed entirely. As I pointed out in anther reply, the UDF is currently undergoing a re-write.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

  • 1 month later...

Thanks.

I have a work-around for that. I'll change it in the next few days and upload the changes. Alternately I'll just change "name like" to "name =" since I don't think it will effect anything anyway.

Just wanted to point out that with SQL you can use a percent sign as a wildcard, so a very convenient way to get rid of several services in one call with the current code is to simply do this:

_Service_Delete("MyService_%")

This will delete all services that begin with "MyService_" (MyService_WatchFiles, MyService_CleanTempFiles, or whatever).

Excellent UDF's! Please be sure to submit for inclusion in the AutoIt distribution when you're comfortable with it!

Edit: After reviewing the code, I see the functions return right after seeing the first item, so the wildcard thing doesn't work this way.

Edited by c0deWorm

My UDFs: ExitCodes

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...