How to execute openssl command at shutdown and reboot?

6.5k Views Asked by At

I want to encrypt a file and log the time at shutdown or reboot.
Here is what i do.
1.edit a bash script file to execute at shutdown or reboot.

vim log.sh
key="123456"
openssl enc -des3 -a -salt -in $HOME/test -k ${key} -out $HOME/test.asc
date >>  /home/log.info

2.edit a log.service

sudo vim /etc/systemd/system/log.service
[Unit]
Description=Run command at shutdown
Before=shutdown.target reboot.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/bin/bash /home/log.sh


[Install]
WantedBy=multi-user.target

3.systemctl enable log.service
4.reboot

After reboot i found that there is a date info in /home/log.info ,it means date >> /home/log.info executed,no $HOME/test.asc there,it means openssl enc -des3 -a -salt -in $HOME/test -k ${key} -out $HOME/test.asc not executed.
The commands can run successfully in terminal .

key="123456"
openssl enc -des3 -a -salt -in $HOME/test -k ${key} -out $HOME/test.asc

How to fix my log.service file /etc/systemd/system/log.service to make openssl command executed at shutdown and reboot?

2

There are 2 best solutions below

0
jayant On BEST ANSWER

The issue is that ${HOME} doesn't expand to what you expect. When I try it on my system it expands to nothing. So ${HOME}/test becomes /test. You can check this by redirecting the error output for your openssl command in log.sh:

openssl enc -des3 -a -salt -in $HOME/test -k ${key} -out $HOME/test.asc 2> /home/log.error

Solution 1:

Use absolute paths in log.sh

Solution 2:

Add User= in service section of log.service. In this case make sure that the user has rights to write to the different locations where you want to write. For reference see systemd.exec

$USER, $LOGNAME, $HOME, $SHELL

User name (twice), home directory, and the login shell. The variables are set for the units that have User= set, which includes user systemd instances

0
Mark Stosberg On

Before= is documented in man systemd.unit. It's not intended for this use case. Also documented there is WantedBy= and RequiredBy=. The latter sounds like what is desired here, but your logging fails, it could block shutdown. WantedBy= won't block shutdown if it fails. Read about them both and see which one fits your case better.

I would recommend a file structure like this:

```

[Unit]
Description=Run command at shutdown

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/bin/bash /home/log.sh


[Install]
WantedBy=shutdown.target reboot.target

```

Your Install block was setting the service to start at boot time, which is not what you want. The new syntax will set the service to be active at shutdown time when you use systemctl enable log.service to enable it.

I have not tested this method of run-at-shutdown with systemd. Let us know how it works!