[CentOS] Running script before reboot or shutdown

Tue Dec 22 15:50:13 UTC 2020
Carlos Lopez <clopmz at outlook.com>

Thanks centos2 .... but regarding your example, I cannot see where you configure that this services needs to be stopped before anyone else....


On 22/12/20, 15:22, "CentOS on behalf of centos2 at foxengines.net" <centos-bounces at centos.org on behalf of centos2 at foxengines.net> wrote:

    Hi,

    On Tue, Dec 22, 2020, at 06:51, Carlos Lopez wrote:
    > I am trying to configure a script as a systemd service to run first when a shutdown or reboot is called. This script execute some scp commands to copy some files to other machines. My actual defined systemd’s file is:
    > 
    > [Unit]
    > Description=Remote copy some files before reboot/shutdown
    > Before=poweroff.target halt.target shutdown.target reboot.target
    > DefaultDependencies=no
    > 
    > [Service]
    > Type=simple
    > ExecStart=/bin/true
    > ExecStop=/usr/local/bin/remote_copy
    > RemainAfterExit=yes
    > 
    > [Install]
    > WantedBy=multi-user.target
    > 
    > But it doesn’t work. “remote_copy” is working when it is executed from root shell. I am using CentOS-8 fully patched release.
    > 
    > Any idea what am I doing wrong?

    I don't have a CentOS 8 machine to test on but on a CentOS 7.9, this works for me:

    /etc/systemd/system/shutdown-test.service

    ------------------------------------------------------
    [Unit]
    Description=Remote copy some files before reboot/shutdown

    [Service]
    Type=oneshot
    ExecStart=/bin/true
    ExecStop=/usr/local/bin/remote_copy
    RemainAfterExit=true

    [Install]
    WantedBy=multi-user.target
    ------------------------------------------------------

    the mode and contents of remote_copy:

    -rwxr-xr-x 1 root root 44 Dec 22 08:23 /usr/local/bin/remote_copy

    ------------------------------------------------------
    #!/bin/bash

    date >> /tmp/remote_copy_result
    ------------------------------------------------------

    After enabling the service and rebooting, I get a file in /tmp/remote_copy_result that contains the date.

    My success is attributable not to me but to this post:
    https://unix.stackexchange.com/questions/39226/how-to-run-a-script-with-systemd-right-before-shutdown
    Your unit file seems similar but when I used it, it didn't work on my CentOS 7.9 system either.
    _______________________________________________
    CentOS mailing list
    CentOS at centos.org
    https://lists.centos.org/mailman/listinfo/centos