首页 文章

从可执行文件创建Windows服务

提问于
浏览
264

有没有快速的方法,给定一个可执行文件,创建一个Windows服务,启动时启动它?

6 回答

  • 176

    要从可执行文件创建Windows服务,可以使用 sc.exe

    sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"
    

    您必须在实际的 exe 路径周围加上引号,并在 binPath= 之后加一个空格 .

    More information on the sc command can be found in Microsoft KB251192 .

    请注意,它不适用于任何可执行文件:可执行文件必须是Windows服务(i.e. implement ServiceMain) . 将非服务可执行文件注册为服务时,尝试启动服务时会出现以下错误:

    错误1053:服务未及时响应启动或控制请求 .

    有些工具可以从任意的非服务可执行文件创建Windows服务,请参阅其他答案以获取此类工具的示例 .

  • 4

    使用NSSM( the non-Sucking Service Manager )将.BAT或任何.EXE文件作为服务运行 .

    http://nssm.cc/

    • Step 1 :下载NSSM

    • Step 2 :使用 nssm.exe install [serviceName] 安装您的服务

    • Step 3 :这将打开一个GUI,您将使用它来查找可执行文件

  • 361

    延伸(Kevin Tong)回答 .

    Step 1: 下载并解压缩nssm-2.24.zip

    Step 2: 从命令行类型:

    C:\> nssm.exe install [servicename]

    它将打开如下GUI(示例是UT2003服务器),然后只需将其浏览到:yourapplication.exe

    enter image description here

    更多信息:https://nssm.cc/usage

  • 76

    许多现有答案包括安装时的人为干预 . 这可能是一个容易出错的过程 . 如果您有许多可执行文件想要作为服务安装,那么您要做的最后一件事是在安装时手动执行它们 .

    针对上述场景,我创建了serman,一个命令行工具,用于将可执行文件安装为服务 . 您需要编写的所有内容(只编写一次)是一个简单的服务配置文件以及您的可执行文件 . 跑

    serman install <path_to_config_file>
    

    将安装该服务 . 全部记录了 stdoutstderr . 有关详细信息,请查看project website .

    工作配置文件非常简单,如下所示 . 但它也有许多有用的功能,如下面的 <env><persistent_env> .

    <service>
      <id>hello</id>
      <name>hello</name>
      <description>This service runs the hello application</description>
    
      <executable>node.exe</executable>
    
      <!-- 
           {{dir}} will be expanded to the containing directory of your 
           config file, which is normally where your executable locates 
       -->
      <arguments>"{{dir}}\hello.js"</arguments>
    
      <logmode>rotate</logmode>
    
      <!-- OPTIONAL FEATURE:
           NODE_ENV=production will be an environment variable 
           available to your application, but not visible outside 
           of your application
       -->
      <env name="NODE_ENV" value="production"/>
    
      <!-- OPTIONAL FEATURE:
           FOO_SERVICE_PORT=8989 will be persisted as an environment
           variable to the system.
       -->
      <persistent_env name="FOO_SERVICE_PORT" value="8989" />
    </service>
    
  • 9

    这些额外的东西证明是有用的..需要作为 administrator 执行

    sc install <service_name> binpath=<binary_path>
    sc stop    <service_name>
    sc queryex <service_name>
    sc delete  <service_name>
    

    如果您的服务名称包含任何空格,请用“引号”括起来 .

  • 0

    我为此测试了一个好产品:AlwaysUp . 不是免费的,但他们有30天的试用期,所以你可以尝试一下......

相关问题