Introduction
Under Linux systems, you systemd
can 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 yum
or apt
other 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.service
file
$ 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.conf
Enter the following
if $programname == 'hello' then /root/hello.log
& stop
Combined with hello.service
the StandardOutput, StandardError, and SyslogIdentifier configuration items, hello.sh
the 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/syslog
or/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 systemd
command managementhello
# 启动hello
systemctl start hello
# 停止hello
systemctl stop hello
# 重启hello
systemctl restart hello
# 查看hello状态
systemctl status hello
Configure hello
auto-start at power on
systemctl enable hello