How to configure a command, script, or daemon to run after boot has finished in RHEL 7

环境

  • Red Hat Enterprise Linux (RHEL) 7
  • systemd

问题

  • How can we configure a command, script, application, or daemon to run after all other service scripts and systemd init tasks?

决议


Disclaimer: The following information has been provided by Red Hat, but is outside the scope of the posted Service Level Agreements and support procedures. Red Hat does not support the implementation of custom scripts, including custom systemd startup scripts. This article is provided as a how-to and Red Hat will not troubleshoot any issues after the implementation of the steps provided here. The intent of this article is to provide information to accomplish the system's needs. Use of the information in this article at the user's own risk.


  • For RHEL 5 and RHEL 6 configuration:

1. Create a new ​​/etc/systemd/system/very-last.service​​ file with the following content:

​Raw​

[Unit]
Description=Very last service
After=default.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/very-last

[Install]
WantedBy=default.target

2. Reload ​​systemd​​ daemon:

​Raw​

# systemctl daemon-reload

3. Enable the newly created service ​​very-last​​:

​Raw​

# systemctl enable very-last

4. Create the custom script specified in ​​ExecStart=​​, in this case ​​/usr/local/sbin/very-last​​:

​Raw​

# echo '#!/bin/bash' > /usr/local/sbin/very-last

5. Set the permissions to it:

​Raw​

# chmod 700 /usr/local/sbin/very-last

Note: if SELinux is ​​enforcing​​, run ​​restorecon -Fvvv /usr/local/sbin/very-last​​ to set the context.

6. Edit ​​/usr/local/sbin/very-last​​ to include desired commands

7. Reboot the system to test it.

8. After boot, use ​​systemd-analyze plot > file.svg​​ to generate an image of the boot process for inspection. There could be one or two short-lived services starting after ​​very-last.service​​. If that's a problem, modify ​​/etc/systemd/system/very-last.service​​ to set ​​Type=idle​​ and if the script could take more than 90 secs to run, also set ​​TimeoutStartSec=0​​.

根源

With the switch to ​​systemd​​ in RHEL 7, ​​rc.local​​ no longer runs near the end of the boot process.

Instead of using ​​rc.local​​, create a custom service unit configured with ​​After=default.target​​ and ​​WantedBy=default.target​​ to launch a script, command, or series of commands.