如何在Linux关闭之前立即使用systemd运行脚本

时间:2020-02-23 14:40:23  来源:igfitidea点击:

在本文中,我将共享示例和示例systemd单元服务文件,以便在CentOS/RHEL 7/8 Linux关机之前立即使用systemd运行脚本。
使用此systemd单元文件,我们可以在Linux中关闭之前将某些命令或者脚本作为最后一个服务运行。

现在,理想情况下,任何系统服务都可以在关机阶段通过" ExecStop"调用,而在启动阶段通过" ExecStart"调用。
但是这里我们的要求几乎没有什么不同,我们希望在关闭阶段之前使用systemd运行脚本。
现在可以正常关闭或者重新启动。

第1步:systemd概述

希望我们已经熟悉以下主题

  • systemd概述以及它与旧版SysV脚本的区别

  • 如何在Linux中创建systemd单位文件

创建示例脚本

现在要在关机之前立即使用systemd运行脚本,我们需要一个脚本或者命令。
为了本文的方便,我将使用我的另一篇来自/tmp/startup_script.sh的脚本。
该脚本将循环运行3分钟,以检查并确保该脚本不会由于关机而被杀死。
我们希望脚本运行并停止关闭,直到完全执行

# cat /tmp/startup_script.sh
#!/bin/bash
z=0
for i in {1..3}; do
    sleep 1m
    ((z++))
	echo ""
done

提供脚本的可执行权限

[root@centos-8 ~]# chmod u+x /tmp/startup_script.sh

创建单元文件以在关机前立即使用systemd运行脚本

现在,如第1步中突出显示的那样,我已经写了另一篇文章,其中包含创建新的systemd单元文件的步骤。

其中我们将在/etc/systemd/system下的systemd单元文件命名为run-before-shutdown.service
以下是run-before-login-prompt.service的内容

[root@centos-8 ~]# cat /etc/systemd/system/run-before-shutdown.service
[Unit]
Description=Run my custom task at shutdown
DefaultDependencies=no
Before=shutdown.target
[Service]
Type=oneshot
ExecStart=/tmp/startup_script.sh
TimeoutStartSec=0
[Install]
WantedBy=shutdown.target

这里的主要任务是由Before = shutdown.target和TimeoutStartSec = 0完成的。
有关更多详细信息,请查看systemd.service的手册页。

TimeoutStartSec=   	When a service doesn't signal start-up completion within TimeoutStartSec, systemd considers the service failed; 
			for long-running shell scripts it is essential to modify TimeoutStartSec or disable the timeout logic altogether 
			as above, with TimeoutStartSec=0. See man systemd.service for more details.
Before=   		If the script needs to be run before other services--for example, prior to starting sshd or console/graphical 
			logins ensure there is a Before=XYZ.service in the [Unit] section and a corresponding RequiredBy=XYZ.service 
			in the [Install] section.

刷新systemd配置文件

[root@centos-8 ~]# systemctl daemon-reload

启用脚本以在下次启动时自动启动

[root@centos-8 ~]# systemctl enable run-before-shutdown.service
Created symlink /etc/systemd/system/shutdown.target.wants/run-before-shutdown.service → /etc/systemd/system/run-before-shutdown.service.

验证systemd单元文件配置

现在,既然我们完成了systemd的设置。
让我们验证我们的配置。

[root@centos-8 ~]# reboot

我们正在使用Oracle VirtualBox,因此重新启动后,我们将检查虚拟机的控制台

正如预期的那样,我们看到我们的systemd服务正在运行,并且不允许关闭操作完成。