खोज…


जांचें कि क्या कोई सेवा स्थापित है

यह उदाहरण दिखाता है कि आप जांच सकते हैं कि कोई सेवा पहले से मौजूद है ( यानी , मशीन पर स्थापित है) या नहीं। इस कोड के लिए केवल सबसे कम आवश्यक विशेषाधिकारों की आवश्यकता होती है, इसलिए प्रत्येक प्रक्रिया चेक का प्रदर्शन कर सकती है, इससे कोई फर्क नहीं पड़ता कि सुरक्षा किस स्तर पर चल रही है।

#define UNICODE
#define _UNICODE
#include <Windows.h>
#include <string>
#include <iostream>

enum Result
{
   unknown,
   serviceManager_AccessDenied,
   serviceManager_DatabaseDoesNotExist,
   service_AccessDenied,
   service_InvalidServiceManagerHandle,
   service_InvalidServiceName,
   service_DoesNotExist,
   service_Exist
};

Result ServiceExists(const std::wstring &serviceName)
{
   Result r = unknown;

   // Get a handle to the SCM database
   SC_HANDLE manager = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, GENERIC_READ);
   
   if (manager == NULL)
   {
      DWORD lastError = GetLastError();
      
      // At this point, we can return directly because no handles need to be closed.
      if (lastError == ERROR_ACCESS_DENIED)
         return serviceManager_AccessDenied;
      else if (lastError == ERROR_DATABASE_DOES_NOT_EXIST)
         return serviceManager_DatabaseDoesNotExist;
      else
         return unknown;
   }

   SC_HANDLE service = OpenService(manager, serviceName.c_str(), GENERIC_READ);
   
   if (service == NULL)
   {
      DWORD error = GetLastError();
      
      if (error == ERROR_ACCESS_DENIED)
         r = service_AccessDenied;
      else if (error == ERROR_INVALID_HANDLE)
         r = service_InvalidServiceManagerHandle;
      else if (error == ERROR_INVALID_NAME)
         r = service_InvalidServiceName;
      else if (error == ERROR_SERVICE_DOES_NOT_EXIST)
         r = service_DoesNotExist;
      else
         r = unknown;
   }
   else
      r = service_Exist;

   if (service != NULL)
      CloseServiceHandle(service);

   if (manager != NULL)
      CloseServiceHandle(manager);
   
   return r;
}

int main()
{
   std::wstring serviceName = L"MSSQL$SQLEXPRESS";  // name of the service to check
   Result result = ServiceExists(serviceName);
   if (result == service_Exist)
      std::wcout << L"The service '" << serviceName << "' exists." << std::endl;
   else if (result == service_DoesNotExist)
      std::wcout << L"The service '" << serviceName << "' does not exist." << std::endl;
   else
      std::wcout << L"An error has occurred, and it could not be determined whether the service '" << serviceName << "' exists or not." << std::endl;
}

एपीआई संदर्भ:



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow