09 August, 2007

HowTo remove service in Windows

Sometimes it is necessary to remove service from the Service List in the Windows Managment Console.
In the past I used program, which I compiled from the MSDN's sources (MSDN Library - October 2001: Samples\VC98\sdk\winbase\winnt\service).

But I found another way: Windows XP contains special program SC.exe, which can communicates with the Service Controller and installed services (start, stop, remove, create, query, etc.).
After that I use this command in my shell scripts.

E.g.: for removal of MySQL service, execute command:
sc delete MySQL
(! You may restore MySQL service via command mysqld-nt.exe --install)

But if you want to do this from your C++ program, you may use sample's sources from MSDN.

Part of these is listed below:


service.c
...
void CmdRemoveService()
{
SC_HANDLE schService;
SC_HANDLE schSCManager;

schSCManager = OpenSCManager(
NULL, // machine (NULL == local)
NULL, // database (NULL == default)
SC_MANAGER_ALL_ACCESS // access required
);
if ( schSCManager )
{
schService = OpenService(schSCManager, TEXT(SZSERVICENAME), SERVICE_ALL_ACCESS);

if (schService)
{
// try to stop the service
if ( ControlService( schService, SERVICE_CONTROL_STOP, &ssStatus ) )
{
_tprintf(TEXT("Stopping %s."), TEXT(SZSERVICEDISPLAYNAME));
Sleep( 1000 );

while( QueryServiceStatus( schService, &ssStatus ) )
{
if ( ssStatus.dwCurrentState == SERVICE_STOP_PENDING )
{
_tprintf(TEXT("."));
Sleep( 1000 );
}
else
break;
}

if ( ssStatus.dwCurrentState == SERVICE_STOPPED )
_tprintf(TEXT("\n%s stopped.\n"), TEXT(SZSERVICEDISPLAYNAME) );
else
_tprintf(TEXT("\n%s failed to stop.\n"), TEXT(SZSERVICEDISPLAYNAME) );

}

// now remove the service
if( DeleteService(schService) )
_tprintf(TEXT("%s removed.\n"), TEXT(SZSERVICEDISPLAYNAME) );
else
_tprintf(TEXT("DeleteService failed - %s\n"), GetLastErrorText(szErr,256));


CloseServiceHandle(schService);
}
else
_tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr,256));

CloseServiceHandle(schSCManager);
}
else
_tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
}
...

2 comments:

Anonymous said...

Great stuff:

I used it to remove this infamous "ICF service" (malware) "Internet Countermeasures Framework"

O23 - Service: MS Internet Countermeasures Framework (ICF) - Unknown owner - C:\WINDOWS\System32:svchost.exe (file missing)

Anonymous said...

Thank you very much, this was exactly what i needed. I have installed oracle and the uninstall was not in the add/remove programs list. so i had to install it again in order to uninstall it. But it was not letting me to install because the services are running.
so this made my plan possible :)