Skip to content

自启动脚本

一、centOS

1.1 增加脚本

#进入脚本目录
cd /etc/init.d/
vi shell

加入以下内容,注意必须要加# chkconfig: 2345 99 01这里是权限的判断

#!/bin/bash
# chkconfig: 2345 99 01
source /etc/profile

case "$1" in
"start")
echo 'start'
;;
"stop")
echo 'stop'
;;
"restart")
echo 'restart'
;;
*)
usage;;
esac

三、增加服务

chmod a+x shell
chkconfig --add shell
#设置开机自启动
chkconfig shell on

四、debian

4.1 通过update-rc.d添加

/etc/init.d/目录下创建一个服务脚本vi /etc/init.d/server,添加以下内容:

注意,BEGIN INIT INFO必须要有Default-Start和Default-Stop,将 Default-StartDefault-Stop 字段设置为适当的运行级别, 这样 update-rc.d 命令就能正确识别并将服务添加到开机自启动中

#!/bin/bash
# BEGIN INIT INFO
# Provides: server
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop server service
# END INIT INFO

case "$1" in
  start)
    echo "Starting server service..."
    ;;
  stop)
    echo "Stopping server service..."
    ;;
  restart)
    echo "Restarting server service..."
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac

10.2 通过systemd添加

10.3 创建并启动

/etc/systemd/system/目录下创建一个.service文件,例如server.service

nano /etc/systemd/system/server.service

在该文件中添加以下内容:

[Unit]
Description=server startup script

[Service]
ExecStart=/path/to/script/start.sh

[Install]
WantedBy=multi-user.target

替换/path/to/your/script.sh为你的脚本文件路径。

  1. 设置自启动服务: 启用该服务使其在启动时自动运行。

    systemctl enable server.service
  2. 启动服务(可选): 你可以手动启动服务,检查其运行情况。

    systemctl start server.service
  3. 检查状态: 查看服务的状态,确认无误。

    systemctl status server.service

10.4 重新加载

当配置文件有变化时,需要重载配置才可生效。两种方式都是

#重载配置
systemctl daemon-reload
#重新设置自启动
systemctl enable server.service