[Linux] Use systemd to control custom scripts and configure boot startup and log redirection

Introduction

Under Linux systems, you systemdcan use to conveniently control 自定义shell脚本starting and stopping, configure background operation, enable auto-start and log redirection.

To use systemd, you need to install it firstsystemd

Installsystemd

If it is not installed on the Linux server systemd, you can use the yumor aptother commands to install it.systemd

# yum
yum install systemd
# apt
apt install systemd

Edit custom shell scripthello.sh

vim /root/hello.sh
Enter the following content to save

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

This script only outputs the current time every 5 seconds (format 2023-07-10 15:43:35)
to modify the script execution permissions
chmod +x /root/hello.sh

Edit hello.servicefile

$ vim /lib/systemd/system/frps.service
Write content

[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

Adding /etc/rsyslog.d/newhello.conf

vim /etc/rsyslog.d/hello.confEnter the following

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

Combined with hello.servicethe StandardOutput, StandardError, and SyslogIdentifier configuration items, hello.shthe output will be redirected to the file /root/hello.log.

Restartrsyslog

The redirection log configuration will not take effect until restarting rsyslog, otherwise the log will be output to
/var/log/syslogor/var/log/messages
systemctl restart rsyslog

Notice

The above configuration is effective in practice in centos system.
Under Ubuntu system, replace the following modifications:

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=hello
# 改成下面
StandardOutput=file:/root/hello.log
StandardError=file:/root/hello.log

Use systemdcommand managementhello

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

Configure helloauto-start at power on

systemctl enable hello

Guess you like

Origin blog.csdn.net/u011308433/article/details/131640545