Centos 实现开机自启动脚本并打印日志

本文介绍CentOS7系统中三种开机启动自定义脚本的方法:通过rc-local服务、使用chkconfig添加系统启动脚本及利用systemctl添加自定义启动服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

centos7开机启动自定义脚本大致分为一下几种方式
一、通过CentOS7的rc-local服务启动
      编辑rc.local文件(没有就自己建)

vim /etc/rc.d/rc.local
执行命令以sudo执行,不然可能会出现权限问题(楼主踩过的坑......),打印日志方便调试过程,&表示后台运行,故可能需要等待一段时间才能访问服务。

#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
 
exec 2> /tmp/rc.local.log      # send stderr from rc.local to a log file
exec 1>&2                      # send stdout to the same log file
echo "rc.local started"        # show start of execution
set -x
 
touch /var/lock/subsys/local
cd /opt/code_linux_x64/     
sudo sh run.sh &               # 以root执行,不然可能会出现权限错误,&表示后台执行
 
# 脚本执行完后也给个日志
echo "rc.local completed"
为rc.local添加执行权限,CentOS7默认为rc.local降级了,所以给他开开执行权限。

chmod u+x /etc/rc.d/rc.local
最后查看一下rc.local服务是否启动:

systemctl status rc-local.serives
 
启动命令 
systemctl enable rc-local.service
systemctl start rc-local.service
 
查看服务
ps -ef|grep mysql ##mysql为查询的名称
 出现错误则自自己分析 日志文件,不同脚本会有不同错误,无法说明。

二、通过Linux下的chkconfig添加系统启动脚本
1、在 /etc/rc.d/init.d 目录下新增脚本文件 run.sh

      切记前三行不可少,那不是注释!!!

       第一行#!/bin/bash是指此脚本使用/bin/bash来解释执行

       第二行告诉chkconfig缺省启动的运行级以及启动和停止的优先级。如果某服务缺省不在任何运行级启动,那么使用 - 代替运行级。 

      第三行对服务进行描述,可以用\ 跨行注释,测试瞎写就行。 

详细请自行了解 chkconfig命令,在这里不做过多解释(废话)。

run.sh文件:

#!/bin/bash
# chkconfig: 2345 10 90
# description: 开机自启脚本
###cd /opt/codesec_linux_x64/
####sh run.sh &
 
exec 2> /tmp/rc.local.log      # send stderr from rc.local to a log file
exec 1>&2                      # send stdout to the same log file
echo "rc.local started"        # show start of execution
set -x
 
touch /var/lock/subsys/local
cd /opt
sudo sh scanStart.sh &               ## 以root执行,不然可能会出现权限错误,&表示后台执行
 
# 脚本执行完后也给个日志
echo "rc.local completed"
 scanStart.sh文件:

echo "This is a test message"  ###请自行实现业务脚本,此处不做分享
reboot后日志文件: 

 

2、增加脚本的可执行权限

chmod +x  /etc/rc.d/init.d/run.sh
 
chmod +x  vim /opt/scanStart.sh
3、添加脚本到开机自动启动项目中

chkconfig命令主要用来更新(启动或停止)和查询系统服务的运行级信息。谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接。

cd /etc/rc.d/init.d
chkconfig --add run.sh
chkconfig run.sh on
最后提醒,如果出现问题请自行日志调试。(废话)

三、使用CentOS7 systemctl 添加自定义系统启动自启服务

第一位只是简要的使用,第二位详细说明了各个参数的作用,不废话请参考一下两位的解释:
--------------------- 
作者:邪恶八进制 
来源:优快云 
原文:https://blog.youkuaiyun.com/weixin_38652136/article/details/85775789 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值