Skip to content

OpenWrt系统下注册service服务

约 528 字大约 2 分钟

OpenWrt

2025-05-06

前言

在 OpenWrt 系统中也想把某些脚本或者软件注册为系统服务,实现当系统启动时自动启动,并且可以通过系统服务来管理,那么就可以用service来实现。

1. 注册服务

可以启用procd管理。例如,我们有一个httpRandomMusic.py的脚本实现了某些功能,脚本放在哪里都可以,但要注意给执行权限,那么我们可以编写启动脚本,如下所示:

#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1  # 启用 procd 管理

start_service() {
    procd_open_instance
    procd_set_param command /bin/sh -c '/usr/bin/python3 /usr/bin/httpRandomMusic.py >> /var/log/http-random-music.log 2>&1'
    procd_set_param respawn        # 如果崩溃了自动重启
    procd_close_instance
}

注意:最好是在VScode或者其他编辑器下进行,不要用 Windows 自带的记事本编辑,因为会涉及到换行符(LF/CRLF)的问题,Windows 下默认会使用CRLF换行符,这是隐藏字符默认不显示,但是放在 Linux 环境下执行就会报错。还有就是,这个启动脚本文件没有后缀名。

接着,把这个启动脚本放在/etc/init.d目录下,并且执行chmod +x赋予执行权限,然后就可以在 OpenWrt 系统 Web 页面上的系统->启动项下看到它了。

2. 管理服务

我们可以通过service命令来查看所有服务的运行状态。实际上service <service-name> <command>命令等同于运行/etc/init.d/<service-name> <command>。例如:

/etc/init.d/network restart
service dnsmasq restart
service network reload
service uhttpd enable

每个服务可能定义了不同的附加命令,如 reload_config、dump、check 等。可以用/etc/init.d/<service-name>service <service-name> help来查看支持的命令列表。例如:

# 输入:
service dockerman help
# 输出:
Available commands:
        start           Start the service
        stop            Stop the service
        restart         Restart the service
        reload          Reload configuration files (or restart if service does not implement reload)
        enable          Enable service autostart
        disable         Disable service autostart
        enabled         Check if service is started on boot
        add_ports       Add allowed ports based on the container ID(s)
        convert         Convert Ac allowed container to AC allowed ports
        running         Check if service is running
        status          Service status
        trace           Start with syscall trace
        info            Dump procd service info