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

简介

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

要使用 systemd ,需要先安装 systemd

安装systemd

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

# yum
yum install systemd
# apt
apt install systemd

编辑自定义shell脚本hello.sh

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

#!/bin/sh
while true
do
    date +'%Y-%m-%d %H:%M:%S'
    sleep 5
done

该脚本只是隔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

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

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

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

结合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

使用systemd命令管理hello

# 启动hello
systemctl start hello
# 停止hello
systemctl stop hello
# 重启hello
systemctl restart hello
# 查看hello状态
systemctl status hello

配置hello开机自启

systemctl enable hello

猜你喜欢

转载自blog.csdn.net/u011308433/article/details/131640545