如何仅在关机时(而不是在重启时)使用systemd运行脚本
我希望我们已经熟悉systemd以及SysV和systemd之间的基本区别。
让我们看看如何仅在关机时使用systemd运行脚本。
不应在重新启动时调用此脚本,因为理想情况下,每个脚本也会在重新启动阶段被调用。
作为系统管理员,可能会出现"我们只想在关机时而不是在重启时运行脚本"的情况。
例如在关机时使用脚本或者命令执行某些备份或者任何其他任务。
我们还可以使用以下步骤来调用命令,这些命令仅在Linux中关闭时才能调用。
创建一个示例脚本
现在要仅在使用systemd的情况下在关闭时运行脚本,我们需要一个脚本。
下面是一个虚拟脚本,它我们识别是在reboot.target
还是shutdown.target
处调用了脚本。
通过systemctl list-jobs
,我们知道当前活动和正在运行的目标。
因此,该脚本仅应在shutdown.target
或者reboot.target
上运行
[root@centos-8 ~]# cat /tmp/script.sh #!/bin/bash # Run script with systemd at shutdown only case in start) systemctl list-jobs | egrep -q 'reboot.target.*start' && echo "starting reboot" >> /tmp/file systemctl list-jobs | egrep -q 'shutdown.target.*start' && echo "starting shutdown" >> /tmp/file ;; stop) systemctl list-jobs | egrep -q 'reboot.target.*start' || echo "stopping" >> /tmp/file ;; esac
我还编写了一个stop函数,但是无论如何都不会调用它,只是为了证明这个事实是必需的。
在这种情况下,只有在关闭时而不是在重新启动时,才会调用ExecStart
来使用systemd运行脚本。
创建单元文件以仅在关机时使用systemd运行脚本
我已经写了另一篇文章,介绍了创建系统服务单元文件的步骤和示例。
其中我们将在/etc/systemd/system
下创建名为myscript.service
的systemd单元文件。
以下是我们的systemd单位文件,我们将使用该文件仅在关机时(而不是在重启时)使用systemd运行脚本
[root@centos-8 ~]# cat /etc/systemd/system/myscript.service [Unit] Description=Run my custom task at shutdown only DefaultDependencies=no Conflicts=reboot.target Before=poweroff.target halt.target shutdown.target Requires=poweroff.target [Service] Type=oneshot ExecStart=/tmp/script.sh start RemainAfterExit=yes [Install] WantedBy=shutdown.target
另请阅读:
我们还可以使用列出的脚本或者自定义工具的说明列表来创建自己的手册页。
在实时生产环境中,始终建议为我们开发的每个脚本或者工具也创建并发布手册页。
这是在systemd.unit和systemd的手册页中。
服务
如果一个单元在另一个单元上设置了"冲突=",则启动前者将停止后者,反之亦然
Before =
它们配置单元之间的排序依赖性。Requires
配置其他单元上的需求依赖关系。
如果激活了此设备,则此处列出的设备也将被激活。类型配置此服务单元的流程启动类型。
简单,派生,oneshot,dbus,通知或者闲置之一。ExecStart
命令及其参数,在启动此服务时执行。RemainAfterExit获取一个布尔值,该值指定即使服务的所有进程都退出,该服务是否也应被视为活动状态。
默认为否。
刷新systemd配置文件
[root@centos-8 ~]# systemctl daemon-reload
启用脚本以在下次启动时自动启动
[root@centos-8 ~]# systemctl enable myscript Created symlink /etc/systemd/system/poweroff.target.wants/myscript.service → /etc/systemd/system/myscript.service. Created symlink /etc/systemd/system/halt.target.wants/myscript.service → /etc/systemd/system/myscript.service.
验证systemd单元文件配置
让我们验证我们的systemd单位文件。
我们将关闭我的CentOS/RHEL 7/8 Linux节点,以检查它是否仅在关机时而不是在重启时运行带有systemd的脚本。
[root@centos-8 ~]# shutdown now
节点启动后,我们检查/tmp/file的内容,该文件是我们从虚拟脚本写入内容的位置
login as: root [email protected]'s password: Last login: Tue Jan 14 22:41:22 2017 from 10.0.2.2 [root@centos-8 ~]# cat /tmp/file starting shutdown
如预期的那样,脚本在关闭时被调用。
现在,让我们重新启动并检查一下。
重新启动之前,我将清理/tmp/file的内容
[root@centos-8 ~]# cat /tmp/file [root@centos-8 ~]#
因此,再次如预期的那样,/tmp/file的内容为空,因此在重新启动时未调用此脚本。