如何将 CLI 应用程序作为 Windows 服务运行?

问题描述:

假设我有一个第三方应用程序执行后台工作,但将所有错误和消息打印到控制台.这意味着,目前,我们必须让用户登录到服务器,并在每次重新启动时重新启动应用程序(双击).

Say I have a third party Application that does background work, but prints out all errors and messages to the console. This means, that currently, we have to keep a user logged on to the server, and restart the application (double-click) every time we reboot.

不太酷.

我有点确定,有一种简单的方法可以做到这一点 - 通用服务包装器,可以使用 stdoutstderr 的日志文件进行配置.

I was kind of sure, that there was an easy way to do this - a generic service wrapper, that can be configured with a log file for stdout and stderr.

我确实检查了 svchost.exe,但是 该站点erl=38DlSPGDLYbS0gWaupyXCw&usg东西.可惜.

I did check svchost.exe, but according to this site, its only for DLL stuff. Pity.

应用程序需要从批处理文件启动.FireDaemon 似乎可以解决问题,但我认为这有点矫枉过正,因为它可以在 不是在这里发明的......

The application needs to be started from a batch file. FireDaemon seems to do the trick, but I think it is a bit overkill, for something that can be done in <10 lines of python code... Oh well, Not Invented Here...

查看 srvany.exe 来自 资源工具包.这将使任何东西都可以作为服务运行.

Check out srvany.exe from the Resource Kit. This will let run anything as a service.

您可以通过 srvany.exe 将服务定义中的参数传递给您的可执行文件,这样您就可以通过如下设置注册表来将批处理文件作为服务运行:

You can pass parameters in the service definition to your executable via srvany.exe so you could run a batch file as a service by seting the registry as follows:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\Parameters]
"Application"="C:\\Windows\\System32\\cmd.exe"
"AppParameters"="/C C:\\My\\Batch\\Script.cmd"
"AppDirectory"="C:\\My\\Batch"

注意:如果您在 RegEdit 中设置这些键而不是使用文件,则您只需要在值中使用单个反斜杠.

Note: if you set up these keys in RegEdit rather than using a file you only need single backslashes in the values.