[Linux]CentoOS下实现开机启动特定程序

2021-09-06 550点热度 1人点赞 0条评论

平时的运维工作中会遇到重启Linux服务器,或者断电后,想要开机自动启动特定的程序,本篇讲总结下开机运行特定程序的方法

通过/etc/rc.local文件

CentOS6等之前的旧版本的系统,基本上都是通过把要运行的程序添加到这个文件,来实现开机启动的

来看下/etc/rc.local

[root@localhost ~]# ll /etc/rc.local
lrwxrwxrwx 1 root root 13 Sep 14  2020 /etc/rc.local -> rc.d/rc.local

实际上/etc/rc.local是/etc/rc.d/rc.local的软链接,实际是/etc/rc.d/rc.local文件

vim /etc/rc.local

#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

sh /opt/test.sh
mount -t nfs -o rw 192.168.1.1:/vol/nfs  /mnt/nfs

以上,需要运行的程序,一行一个,就可以了

CentOS7以后版本,就推荐这个方式了,推荐的方式在后面,那如果要让CentOS7下使用rc.local也是可以的。

# 修改/etc/rc.d/rc.local文件为可执行
chmod +x /etc/rc.d/rc.local

# 修改/etc/rc.d/rc.local 给它添加需要执行的程序,一行一个
vim /etc/rc.d/rc.local

# 生效
source /etc/rc.d/rc.local

CentOS7以后,推荐使用systemctl服务的方式来添加自动启动

通过新建一个简单的服务,然后配置服务自启来实现

  • 假设要开机自动运行/opt/my-auto.sh
  • 新建服务my-auto.service

vim /etc/systemd/system/my-auto.service,内容如下:

(网络准备好以后开始)

[Unit]
Description=Description for run script goes here
After=network.target

[Service]
Type=simple
ExecStart=/var/tmp/run_at_startup_script.sh
TimeoutStartSec=0

[Install]
WantedBy=default.target

或者:

[Unit]
Description="My Auto Service" 

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c "/opt/my-auto.sh 2>&1 /var/log/my-auto.log"

[Install]
WantedBy=multi-user.target
  • 服务加载、启动、关闭和设置开机自启项
# 服务重新加载
systemctl daemon-reload

# 服务开机
systemctl start my-auto

# 设置开机自启
systemctl enable my-auto

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论