[Linux] systemd を使用してカスタム スクリプトを制御し、ブート起動とログ リダイレクトを構成する

導入

Linux システムでは、これsystemdを使用して起動と停止を簡単に制御したり自定义shell脚本、バックグラウンド操作を構成したり、自動起動やログ リダイレクトを有効にしたりできます。

を使用するにはsystemd、まずインストールする必要がありますsystemd

インストールsystemd

Linux サーバーにインストールされていない場合は、または他のコマンドを使用してインストールsystemdできます。yumaptsystemd

# yum
yum install systemd
# apt
apt install systemd

カスタムシェルスクリプトを編集するhello.sh

vim /root/hello.sh
次の内容を入力して保存します

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


このスクリプトは、スクリプトの実行権限を変更するために、5 秒ごとに現在時刻 (形式 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.serviceStandardOutput、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
おすすめ