windows 在远程计算机上重新启动服务的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/266389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 05:40:31  来源:igfitidea点击:

Simplest way to restart service on a remote computer

windowswindows-services

提问by Tomalak

What's the easiest programmatic way to restart a service on a remote Windows system? Language or method doesn't matter as long as it doesn't require human interaction.

在远程 Windows 系统上重新启动服务的最简单的编程方法是什么?只要不需要人际互动,语言或方法并不重要。

回答by Tomalak

As of Windows XP, you can use sc.exeto interact with local and remote services. Schedule a task to run a batch file similar to this:

从 Windows XP 开始,您可以使用sc.exe它与本地和远程服务进行交互。安排任务以运行类似于此的批处理文件:

sc \server stop service
sc \server start service

Make sure the task runs under a user account privileged on the target server.

确保任务在目标服务器上具有特权的用户帐户下运行。

psservice.exefrom the Sysinternals PSToolswould also be doing the job:

psservice.exe来自Sysinternals 的 PSTools也将完成这项工作:

psservice \server restart service

回答by dkretz

DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...

描述: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

EXAMPLE: sc start MyService

示例:sc 启动 MyService

回答by Ta01

If it doesn't require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START

如果它不需要人工交互,这意味着将没有调用此操作的 UI,我认为它会在某个设定的时间间隔重新启动?如果您有权访问机器,则可以设置计划任务以使用旧的 NET STOP 和 NET START 执行批处理文件

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

or if you want to get a little more sophisticated, you could try Powershell

或者如果你想变得更复杂一点,你可以试试Powershell

回答by ambassallo

There will be so many instances where the service will go in to "stop pending".The Operating system will complain that it was "Not able to stop the service xyz." In case you want to make absolutely sure the service is restarted you should kill the process instead. You can do that by doing the following in a bat file

将有很多情况下服务将进入“停止挂起”。操作系统会抱怨它“无法停止服务 xyz”。如果您想绝对确保服务重新启动,您应该终止该进程。您可以通过在 bat 文件中执行以下操作来做到这一点

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

To find out which process is associated with your service, go to task manager--> Services tab-->Right Click on your Service--> Go to process.

要找出与您的服务相关联的进程,请转到任务管理器--> 服务选项卡--> 右键单击​​您的服务--> 转到进程。

Note that this should be a work around until you figure out why your service had to be restarted in the first place. You should look for memory leaks, infinite loops and other such conditions for your service to have become unresponsive.

请注意,这应该是一种解决方法,直到您弄清楚为什么必须首先重新启动服务。您应该寻找内存泄漏、无限循环和其他此类情况,使您的服务变得无响应。

回答by Raz

look at sysinternalsfor a variety of tools to help you achieve that goal. psService for example would restart a service on a remote machine.

查看sysinternals中的各种工具来帮助您实现该目标。例如 psService 将在远程机器上重新启动服务。

回答by JosephStyons

I recommend the method given by doofledorfer.

我推荐 doofledorfer 给出的方法。

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

如果您真的想通过直接 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;

回答by ShaneC

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

从 Powershell v3 开始,PSsessions 允许在远程机器上运行任何本机 cmdlet

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

See herefor more information

请参阅此处了解更多信息

回答by Medos

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

我相信 PowerShell 现在在简单性方面胜过“sc”命令:

Restart-Service "servicename"

回答by Medos

  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
  1. 使用 openscmanager 打开服务控制管理器数据库
  2. 使用 EnumDependService() 获取依赖服务
  3. 使用 ChangeConfig() 停止所有相关服务,如果它们已启动,则向该函数发送 STOP 信号
  4. 停止实际服务
  5. 获取服务的所有服务依赖项
  6. 如果服务已停止,则使用 StartService() 启动所有服务依赖项
  7. 开始实际服务

Thus your service is restarted taking care all dependencies.

因此,您的服务将重新启动,并注意所有依赖项。

回答by Kishore Kumar

This is what I do when I have restart a service remotely with different account

这就是我使用不同帐户远程重新启动服务时所做的

Open a CMD with different login

用不同的登录名打开一个 CMD

runas /noprofile /user:DOMAIN\USERNAME cmd

Use SC to stop and start

使用 SC 停止和启动

sc \SERVERNAME query Tomcat8
sc \SERVERNAME stop Tomcat8
sc \SERVERNAME start Tomcat8