当前位置:   article > 正文

【Linux】使用systemd控制自定义脚本及配置开机自启、日志重定向_systemd开机启动脚本

systemd开机启动脚本

简介

在 Linux 系统下,使用systemd 可以方便地控制 自定义shell脚本启动和停止、配置后台运行、开启自启和日志重定向。

要使用 systemd ,需要先安装 systemd

安装systemd

如Linux服务端上没有安装 systemd,可以使用 yumapt 等命令安装 systemd

# yum
yum install systemd
# apt
apt install systemd
  • 1
  • 2
  • 3
  • 4

编辑自定义shell脚本hello.sh

vim /root/hello.sh
输入以下内容保存

#!/bin/sh
while true
do
    date +'%Y-%m-%d %H:%M:%S'
    sleep 5
done
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

该脚本只是隔5s输出一次当前时间(格式2023-07-10 15:43:35)
修改脚本执行权限
chmod +x /root/hello.sh

编辑hello.service文件

$ vim /lib/systemd/system/frps.service
写入内容

[Unit]
Description=Hello Service
After=network.target syslog.target
Wants=network.target

[Service]
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/root/hello.sh
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=hello

[Install]
WantedBy=multi-user.target
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

/etc/rsyslog.d/新增hello.conf

vim /etc/rsyslog.d/hello.conf输入以下内容

if $programname == 'hello' then /root/hello.log
& stop
  • 1
  • 2

结合hello.service中的StandardOutput、StandardError、SyslogIdentifier配置项,hello.sh的输出将重定向到文件/root/hello.log

重启rsyslog

重定向日志配置要重启rsyslog之后才会生效,否则日志会输出到
/var/log/syslog/var/log/messages
systemctl restart rsyslog

注意

以上配置是在centos系统中实践有效。
在Ubuntu系统下,则替换如下修改:

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=hello
# 改成下面
StandardOutput=file:/root/hello.log
StandardError=file:/root/hello.log
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

使用systemd命令管理hello

# 启动hello
systemctl start hello
# 停止hello
systemctl stop hello
# 重启hello
systemctl restart hello
# 查看hello状态
systemctl status hello
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

配置hello开机自启

systemctl enable hello

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/639438
推荐阅读
相关标签
  

闽ICP备14008679号