UFO ET IT

원격 컴퓨터에서 서비스를 다시 시작하는 가장 간단한 방법

ufoet 2020. 12. 29. 07:35
반응형

원격 컴퓨터에서 서비스를 다시 시작하는 가장 간단한 방법


원격 Windows 시스템에서 서비스를 다시 시작하는 가장 쉬운 프로그래밍 방식은 무엇입니까? 인간의 상호 작용이 필요하지 않는 한 언어 또는 방법은 중요하지 않습니다.


Windows XP부터를 사용 sc.exe하여 로컬 및 원격 서비스와 상호 작용할 수 있습니다 . 다음과 유사한 배치 파일을 실행하도록 작업을 예약합니다.

sc \\ 서버 중지 서비스
sc \\ 서버 시작 서비스

작업이 대상 서버에 대한 권한이있는 사용자 계정으로 실행되는지 확인합니다.

psservice.exe으로부터 시스 인 터널 PsTools에 또한 일을 할 것입니다 :

psservice \\ 서버 재시작 서비스

설명 : SC는 NT 서비스 컨트롤러 및 서비스와 통신하는 데 사용되는 명령 줄 프로그램입니다. 사용법 : sc [명령] [서비스 이름] ...

    The option <server> has the form "\\ServerName"
    Further help on commands can be obtained by typing: "sc [command]"
    Commands:
      query-----------Queries the status for a service, or
                      enumerates the status for types of services.
      queryex---------Queries the extended status for a service, or
                      enumerates the status for types of services.
      start-----------Starts a service.
      pause-----------Sends a PAUSE control request to a service.
      interrogate-----Sends an INTERROGATE control request to a service.
      continue--------Sends a CONTINUE control request to a service.
      stop------------Sends a STOP request to a service.
      config----------Changes the configuration of a service (persistant).
      description-----Changes the description of a service.
      failure---------Changes the actions taken by a service upon failure.
      qc--------------Queries the configuration information for a service.
      qdescription----Queries the description for a service.
      qfailure--------Queries the actions taken by a service upon failure.
      delete----------Deletes a service (from the registry).
      create----------Creates a service. (adds it to the registry).
      control---------Sends a control to a service.
      sdshow----------Displays a service's security descriptor.
      sdset-----------Sets a service's security descriptor.
      GetDisplayName--Gets the DisplayName for a service.
      GetKeyName------Gets the ServiceKeyName for a service.
      EnumDepend------Enumerates Service Dependencies.

    The following commands don't require a service name:
    sc <server> <command> <option>
      boot------------(ok | bad) Indicates whether the last boot should
                      be saved as the last-known-good boot configuration
      Lock------------Locks the Service Database
      QueryLock-------Queries the LockStatus for the SCManager Database

예 : sc start MyService


사람의 상호 작용이 필요하지 않다면이 작업을 호출하는 UI가없고 일정 간격으로 다시 시작될 것이라고 가정합니다. 머신에 대한 액세스 권한이있는 경우 이전 NET STOP 및 NET START를 사용하여 배치 파일을 실행하도록 예약 된 작업을 설정할 수 있습니다.

net stop "DNS Client"
net start "DNS client"

또는 좀 더 정교하게 만들고 싶다면 Powershell을 사용해 볼 수 있습니다.


서비스가 "중지 중지"상태가되는 경우가 너무 많습니다. 운영 체제는 "xyz 서비스를 중지 할 수 없습니다"라고 불평합니다. 서비스가 다시 시작되었는지 확인하려면 대신 프로세스를 종료해야합니다. bat 파일에서 다음을 수행하여이를 수행 할 수 있습니다.

taskkill /F /IM processname.exe
timeout 20
sc start servicename

서비스와 관련된 프로세스를 확인하려면 작업 관리자-> 서비스 탭-> 서비스를 마우스 오른쪽 버튼으로 클릭-> 프로세스로 이동하십시오.

서비스를 처음에 다시 시작해야하는 이유를 파악할 때까지이 문제를 해결해야합니다. 서비스가 응답하지 않는 메모리 누수, 무한 루프 및 기타 조건을 찾아야합니다.


이러한 목표를 달성하는 데 도움이되는 다양한 도구를 sysinternals 에서 확인하십시오 . 예를 들어 psService는 원격 시스템에서 서비스를 다시 시작합니다.


doofledorfer가 제공하는 방법을 권장합니다.

직접 API 호출을 통해 실제로 수행하려면 OpenSCManager 함수 를 살펴보십시오 . 다음은 머신 이름과 서비스를 가져 와서 중지하거나 시작하는 샘플 함수입니다.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;

  1. open service control manager database using openscmanager
  2. get dependent service using EnumDependService()
  3. Stop all dependent services using ChangeConfig() sending STOP signal to this function if they are started
  4. stop actual service
  5. Get all Services dependencies of a service
  6. Start all services dependencies using StartService() if they are stopped
  7. Start actual service

Thus your service is restarted taking care all dependencies.


As of Powershell v3, PSsessions allow for any native cmdlet to be run on a remote machine

$session = New-PSsession -Computername "YourServerName"
Invoke-Command -Session $Session -ScriptBlock {Restart-Service "YourServiceName"}
Remove-PSSession $Session

See here for more information


I believe PowerShell now trumps the "sc" command in terms of simplicity:

Restart-Service "servicename"

ReferenceURL : https://stackoverflow.com/questions/266389/simplest-way-to-restart-service-on-a-remote-computer

반응형