Linux开机启动的多种实现方式

开机启动是运维自动化的重要组成部分。

/etc/rc.local

可将开机启动命令追加到/etc/rc.local中

1
2
# readlink /etc/rc.local
rc.d/rc.local // /etc/rc.d/rc.local

chkconfig

1
2
3
4
5
6
# readlink /etc/init.d
rc.d/init.d // /etc/rc.d/init.d/

chkconfig --add servicename # 使服务会被在/etc/rc.d/rcN.d中赋予K/S入口
chkconfig --level 35 servicename on 或 sudo update-rc.d servicename defaults 95
chkconfig --list
  • 服务脚本必须存放在/etc/ini.d/目录下

  • /etc/ini.d/下的脚本最开始必须包含以下三行

    1
    2
    3
    #! /bin/sh
    # chkconfig: - 58 74 # 分别代表运行级别,启动优先权,关闭优先权,此行代码必须
    # description:

/etc/profile.d/

  • 登陆自动执行(/etc/profile.d/),不仅仅是开机自动执行。

  • 必须是.sh后缀的脚本文件

systemd

1
2
3
4
5
6
7
systemctl list-unit-files --type=service | grep enabled         # 查看允许开机启动的服务进程
systemctl list -units --type=service # 查看所有已启动的服务
systemctl mask daemon.service # 在任何情况下系统启动时都不启动该进程
systemctl enable daemon.service # 设置开机启动
systemctl disable daemon.service # 禁止开机启动
systemctl is-enabled daemon.service # 确认服务是否开机启动
ll /etc/systemd/system/multi-user.target.wants/ # 查看所有开启启动的服务

crontab

1
@reboot root ( sleep 30; sh /path/to/script.sh )    # 经验证,cron配置中支持小括号
  • cron支持的关键字
    1
    2
    3
    4
    5
    6
    7
    8
    @reboot at startup
    @yearly once a year
    @annually ( == @yearly)
    @monthly once a month
    @weekly once a week
    @daily once a day
    @midnight ( == @daily)
    @hourly once an hour