Aide-mémoire Systemd + scripts
Systemd est le système et le gestionnaire de services modernes pour les systèmes d’exploitation Linux, remplaçant les systèmes d’initialisation traditionnels tels que System V et Upstart. Il est responsable de la gestion du démarrage du système, des services et des processus.La commande systemctl est utilisée pour contrôler les unités système, y compris les services, les sockets, les minuteries et les cibles.
- Commandes et options systemctl
- How to run systemd service as specific user and group in Linux
- How to run script with systemd right before shutdown in Linux
- How to read user input during boot stage with systemd in Linux
- How to run script with systemd right before login prompt
- How to run script after N minutes of boot with systemd
- How to run script with systemd at shutdown only (not at reboot)
- How to run script on startup using systemd in Linux
- Step 1: Overview on systemd
- Step 2: Create Sample Script
- Step 3: Create systemd unit file for different scenario
- Step 3.1: Run script at startup with systemd after network becomes reachable
- Step 3.2: Run script at startup with systemd after all systemd services are loaded
- Step 3.3: Run script at startup with systemd after login prompt appears
- Step 4: Verify the systemd unit file configuration
Commandes et options systemctl
systemctl services
Les noms de services typiques suivent une convention liée au logiciel qu’ils gèrent. Par exemple, nginx.service contrôle le serveur Web Nginx, tandis que ssh.service gère le serveur OpenSSH.
Pour vérifier l’état d’un service:
1
systemctl status <service-name>
Pour démarrer un service:
1
systemctl start <service-name>
Pour arrêter un service:
1
systemctl stop <service-name>
Pour relancer un service:
1
systemctl restart <service-name>
Pour recharger un service:
1
systemctl reload <service-name>
Pour activer un service au démarrage:
1
systemctl enable <service-name>
Pour désactiver un service au démarrage:
1
systemctl disable <service-name>
Pour vérifier si un service est activé ou désactivé:
1
systemctl is-enabled <service-name>
Pour afficher les journaux pour un service:
1
journalctl -u <service-name>
systemctl units
Une unité en système est une ressource qui gère le système. Les unités peuvent représenter des services, des sockets, des points de montage, des périphériques et d’autres ressources du système, chacun défini par un fichier de configuration correspondant.
Listing units
Pour lister toutes les unités actives:
1
systemctl list-units
Pour répertorier tous les fichiers unitaires installés:
1
systemctl list-unit-files
Pour énumérer toutes les unités défaillantes:
1
systemctl --failed
Pour filtrer des types d’unités spécifiques (p. ex., services):
1
systemctl list-units --type=service
Utilisation de motifs avec grep:
1
systemctl list-unit-files | grep disabled
Inspecting units
Pour voir le contenu d’un fichier unitaire:
1
systemctl cat <unit-name>
Pour montrer les propriétés d’une unité:
1
systemctl show <unit-name>
Pour énumérer les dépendances d’une unité:
1
systemctl list-dependencies <unit-name>
systemd timers
Les minuteurs système sont des fichiers unitaires qui déclenchent l’exécution de services à des heures ou des intervalles planifiés, remplaçant les tâches de cron traditionnelles.
Pour lister tous les minuteurs actifs:
1
systemctl list-timers
Pour vérifier les détails d’une minuterie:
1
systemctl status <timer-name>
Pour ajouter une nouvelle minuterie:
1
systemctl enable <timer-name>
Pour mettre en pause une minuterie:
1
systemctl stop <timer-name>
Pour supprimer une minuterie:
1
systemctl disable <timer-name>
Etat système
L’état du système dans systemd fait référence à l’état de santé et de fonctionnement global du système, y compris s’il est démarré correctement, fonctionnant correctement ou rencontrant des erreurs.
Pour voir l’état actuel du système:
1
systemctl is-system-running
Pour redémarrer le système:
1
systemctl reboot
Pour éteindre le système:
1
systemctl poweroff
Pour suspendre le système:
1
systemctl suspend
Pour hiberner le système:
1
systemctl hibernate
Commandes et options courantes de journalctl
Pour afficher tous les journaux (affiche l’ensemble du journal système):
1
journalctl
Journaux processus démarrage
Pour afficher les journaux liés au processus de démarrage du système:
1
journalctl -b
Pour afficher les journaux de la chaussure précédente:
1
journalctl -b -1
Pour répertorier les journaux de démarrage précédents:
1
journalctl --list-boots
Journaux spécifiques date et heure données
Pour suivre les journaux en temps réel (tail -f pour afficher en permanence de nouvelles entrées de journal):
1
journalctl -f
Pour afficher les journaux à partir d’une durée relative (par exemple, 1 dernière heure):
1
journalctl --since "1 hour ago"
Pour afficher les journaux des 30 dernières minutes:
1
journalctl --since "30 minutes ago"
Pour afficher les journaux de la semaine dernière:
1
journalctl --since "7 days ago"
Afficher les journaux depuis une date et une heure spécifiques:
1
journalctl --since "2025-03-15 08:00:00"
Pour afficher les journaux jusqu’à une date et une heure spécifiques:
1
journalctl --until "2025-03-15 18:00:00"
Pour afficher les journaux pour une plage de temps spécifique:
1
journalctl --since "2025-03-15 12:00:00" --until "2025-03-15 14:00:00"
Pour afficher les journaux d’un jour spécifique:
1
journalctl --since "2025-03-14" --until "2025-03-14 23:59:59"
Pour voir les journaux d’hier (à partir de minuit de la veille):
1
journalctl --since "yesterday"
Journaux spécifiques applications
Pour filtrer les journaux pour une unité spécifique, par ex. nginx.service:
1
journalctl -u <unit-name>
Pour afficher les journaux du noyau Linux:
1
journalctl -k
Pour afficher les journaux pour un processus utilisateur spécifique, ID utilisateur 1000:
1
journalctl _UID=1000
Pour afficher les journaux pour un exécutable spécifique:
1
journalctl /usr/bin/your_program
Journaux erreurs et alertes
Afficher les journaux avec filtrage de priorité (logs avec la priorité 3 (erreurs) et plus (plus critique)):
1
journalctl -p 3
ou
1
journalctl -p err
Pour afficher uniquement les messages d’erreur, critiques et d’alerte:
1
journalctl -p err..alert
Journaux mainenance
Pour supprimer les journaux de plus de 7 jours:
1
sudo journalctl --vacuum-time=7d
Pour effacer les journaux (limite la taille du journal à 500MB):
1
sudo journalctl --vacuum-size=500M
Pour supprimer les journaux plus anciens qu’une date précise (p. ex., avant le 1er mars 2025):
1
sudo journalctl --vacuum-time="2025-03-01"
Pour effacer les journaux pour un service spécifique (par exemple, nginx):
1
sudo journalctl --vacuum-size=500M -u nginx.service
Pour rincer tous les journaux de journal (DANGEROUS – supprime définitivement tous les journaux!):
1
2
3
sudo journalctl --rotate
sudo journalctl --vacuum-time=1s
Pour supprimer manuellement tous les journaux et redémarrer systemd-journald:
1
2
sudo rm -rf /var/log/journal/*
sudo systemctl restart systemd-journald
FAQ
Comment puis-je vérifier l’état d’un service dans systemd?
Utiliser systemctl status service-name pour vérifier l’état actuel et les journaux d’un service système.
Comment puis-je redémarrer une systemd unit en panne?
Utiliser systemctl restart service-name pour relancer un service. Vérifier les journaux avec journalctl -u service-name
Comment puis-je répertorier toutes les systemd unit?
Exécuter systemctl list-units pour voir les unités actives ou systemctl list-unit-files pour tous les fichiers unitaires installés.
Qu’est-ce qu’un systemd timer et comment puis-je l’utiliser?
Un systemd timer est une unité qui déclenche l’exécution du service à des moments spécifiques. Utiliser systemctl list-timers pour voir les minuteurs actifs.
Comment puis-je désactiver un service dès le démarrage?
Exécuter systemctl disable service-name pour désactiver le service au démarrage.
How to run systemd service as specific user and group in Linux
By default most of the systemd services are configured to run by root user but there is also an option to create a custom systemd service unit file and run it as a speciic user or group or both. So in this article we will check and verify the steps to run systemd service as specific user and group using CentOS/RHEL 7/8 Linux environment.
I have installed Oracle VirtualBox on a Linux server, where I will use a Virtual Machine with RHEL/CentOS 7/8 to verify the steps from this article.
Step 1: Overview on systemd
If you are a beginner to systemd then I would recommend you to also read Overview on systemd and how it is different from legacy SysV scripts before starting with this tutorial.
Step 2: Create user and Group
Now this is an optional steps assuming you already have your user and group ready for next steps. But if you do not then you can follow this article to create a new user and assign a custom group (primary or secondary) to the respective user.
- How to create a new user without using useradd command in Linux
- Steps to add a user to a group or remove a user from a group (primary or secondary) in Linux or Unix
Here I have already created a user deepak who is part of deepak and admin group
1
2
[root@centos-8 ~]# useradd deepak
[root@centos-8 ~]# passwd deepak <-- Here the screen will prompt to assign a new password
To verify the groups of any user
1
2
[root@centos-8 ~]# id deepak
uid=1000(deepak) gid=1000(deepak) groups=1000(deepak),1001(admin)
So we wish to create a systemd service unit file and run systemd service as specific user and group which for us will be deepak user part of admin group
Step 3: Create Sample Script
Create a directory to store your script:
1
mkdir -p /opt/golinuxcloud
We will use our startup_script.sh from older articles with some tweaks to check and run systemd service as specific user and group in Linux
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
if [[ `id -nu` != "deepak" ]];then
echo "Not deepak user, exiting.."
exit 1
fi
SCRIPT_NAME=$(basename -- "$0")
z=0
for i in {1..3}; do
sleep 1m
((z++))
echo "$SCRIPT_NAME: finished minute ${z}" >> /opt/golinuxcloud/file
done
echo "$SCRIPT_NAME: COMPLETELY FINISHED" >> /opt/golinuxcloud/file
So in this script we have added an explicit check for user, so unless the user executing the script is “deepak”, the script will fail to execute. If successful the script will continue to write in /opt/golinuxcloud/file for 3 minutes with 1 minute interval. This will also help us make sure that the script does not exits before completing it’s defined task
Change the ownership of the script file to deepak
1
chown deepak:deepak /opt/golinuxcloud/startup_script.sh
Provide executable permission to the script using chmod command
1
2
3
4
chmod u+x /opt/golinuxcloud/startup_script.sh
ls -l /opt/golinuxcloud/startup_script.sh
-r-xr--r-- 1 deepak deepak 304 Jan 17 01:58 /opt/golinuxcloud/startup_script.sh
We will execute the script manually to make sure it works as expected
1
2
[root@centos-8 ~]# /opt/golinuxcloud/startup_script.sh
Not deepak user, exiting..
Step 4: Create unit file to run systemd service as specific user and group
Now as highlighted under step 1, I have already written another article with the steps to create a new systemd unit file. Here we will name our systemd unit file as run-as-user.service under /etc/systemd/system. Below is the content of run-as-user.service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@centos-8 ~]# cat /etc/systemd/system/run-as-user.service
[Unit]
Description=Run service as user deepak
DefaultDependencies=no
After=network.target
[Service]
Type=simple
User=deepak
Group=admin
ExecStart=/opt/golinuxcloud/startup_script.sh
TimeoutStartSec=0
RemainAfterExit=yes
[Install]
WantedBy=default.target
Here we have defined User=deepak and Group=admin to make sure the script will be executed only as user deepak which is part of admin group.
You can also use many other directives if required in your environment such as WorkingDirectory, EnvironmentFile etc. For more information check man page of systemd.exec
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
Refresh the systemd configuration files
1
systemctl daemon-reload
Next enable the service (if required) to start automatically at boot
1
systemctl enable run-as-user.service
If the service was not in enabled status then you should see below message:
1
Created symlink /etc/systemd/system/shutdown.target.wants/run-as-user.service → /etc/systemd/system/run-as-user.service.
Step 5: Verify the systemd unit file configuration
Now since we are done with the setting up of systemd. Let us verify our configuration. Before starting I have cleared the content of /opt/golinuxcloud/file which is where our script /opt/golinuxcloud/startup_script.sh will place dummy content every minutes for 3 minutes.
We will only start the run-as-user.service runtime as a reboot is not required to validate the configuration here:
1
systemctl restart run-as-user.service
Next check the status of the service
1
2
3
4
5
6
7
8
[root@centos-8 ~]# systemctl status run-as-user.service
● run-as-user.service - Run service as user deepak
Loaded: loaded (/etc/systemd/system/run-as-user.service; enabled; vendor preset: disabled)
Active: active (exited) since Fri 2020-01-17 02:09:32 IST; 2h 31min ago
Process: 24113 ExecStart=/opt/golinuxcloud/startup_script.sh (code=exited, status=0/SUCCESS)
Main PID: 24113 (code=exited, status=0/SUCCESS)
Jan 17 02:09:32 centos-8.example.com systemd[1]: Started Run service as user deepak.
Well looks like everything was good as we were able to run systemd service as specific user and group, you can check the ps status to make sure our script is running using below command:
1
2
3
[root@centos-8 ~]# ps -ef | grep startup
deepak 26877 1 0 04:42 ? 00:00:00 /bin/bash /opt/golinuxcloud/startup_script.sh
root 26890 7625 0 04:42 pts/0 00:00:00 grep --color=auto startup
Now you can monitor the content of /opt/golinuxcloud/file for couple of minutes as configured in the script
1
2
3
4
5
[root@centos-8 ~]# cat /opt/golinuxcloud/file
startup_script.sh: finished minute 1
startup_script.sh: finished minute 2
startup_script.sh: finished minute 3
startup_script.sh: COMPLETELY FINISHED
Lastly I hope the steps from the article to run systemd service as specific user and group in CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: run service as user linux. systemd allow user to start service. systemd start service as user on boot. linux systemd service run as root. Restarting systemd service only as a specific user? systemd services fail with User= in service file. Start process as a specific user. how to run a service a non-root user completely?
How to run script with systemd right before shutdown in Linux
In this article I will share example and sample systemd unit service file to run script with systemd right before shutdown in CentOS/RHEL 7/8 Linux. Using this systemd unit file you can run either some command or script as a last service before shutdown in Linux.
Now ideally any systemd service gets called via ExecStop at shutdown stage and with ExecStart at boot up stage. But here our requirement is little different, we wish to run script with systemd right before shutdown stage. Now this can be a normal shutdown or reboot.
Step 1: Overview on systemd
If you are a beginner to systemd then I would recommend you to also readOverview on systemd and how it is different from legacy SysV scriptsbefore starting with this tutorial.
Step 2: Create Sample Script
Now to run script with systemd right before shutdown we need a script or command. For the sake of this article I will use a script from another article of mine /tmp/startup_script.sh. This script will run for 3 minutes in a loop to check and make sure the script is not killed due to shutdown. We want the script to run and halt the shutdown until completely executed
1
2
3
4
5
6
7
8
# cat /tmp/startup_script.sh
#!/bin/bash
z=0
for i in {1..3}; do
sleep 1m
((z++))
echo ""
done
Provide executable permission to the script
1
chmod u+x /tmp/startup_script.sh
Step 3: Create unit file to run script with systemd right before shutdown
Now as highlighted under step 1, I have already written another article with the steps to create a new systemd unit file. Here we will name our systemd unit file as run-before-shutdown.service under /etc/systemd/system. Below is the content of run-before-login-prompt.service
1
2
3
4
5
6
7
8
9
10
11
12
13
[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
Here the main task is done by Before=shutdown.target and TimeoutStartSec=0. For more details check man page of systemd.service
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
1
2
3
4
5
6
7
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.
Refresh the systemd configuration files
1
[root@centos-8 ~]# systemctl daemon-reload
Enable the script to automatically start at next boot
1
2
[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.
Step 3: Verify the systemd unit file configuration
Now since we are done with the setting up of systemd. Let us verify our configuration.
1
reboot
![[96f9033b5f60b8ac3791da9f96025ce3_MD5.webp]]
We are using Oracle VirtualBox so post reboot we will check the console of our Virtual Machine
As expected we see that our systemd service is running and not allowing shutdown to complete.
Lastly I hope the steps from the article to run script with systemd right before shutdown on CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: run script with systemd right before shutdown. how to execute shell script before shutdown. run script before shutdown linux. run script on shutdown linux
How to read user input during boot stage with systemd in Linux
In this article I will share a sample systemd unit file which can be used to read user input during boot stage using shell script with systemd in RHEL/CentOS 7/8 Linux. It is possible that for a system administrator there are some tasks such as setting hostname or something which requires him/her to read user input during boot stage before login prompt comes up. And then based on the user input certain task is performed using a background script.
This is possible using systemd unit service file in RHEL/CentOS 7/8 Linux.
Step 1: Overview on systemd
If you are a beginner to systemd then I would recommend you to also readOverview on systemd and how it is different from legacy SysV scriptsbefore starting with this tutorial.
Step 2: Create Sample script
We will use a custom small script with until loop to read user input during boot stage. So unless the script gets the user input, it will not allow the boot stage to complete.
1
2
3
4
5
6
[root@centos-8 ~]# cat /tmp/welcome.sh
#!/bin/bash
until [[ -n ${REPLY} ]]; do
read -ep "Enter your name: "
done
echo "WELCOME ${REPLY^^}"; sleep 5
Here the script will prompt “Enter your name” and then will wait for user input. If we call this script at boot up stage then the script will read user input during boot stage and proceed accordingly.
Step 3: Create systemd unit service file to read user input during boot stage
Now we need a systemd unit service file which will call our script at boot stage to read user input. The file should be located in either /usr/lib/systemd/system/ or /etc/systemd/system/. Below is a sample systemd unit service file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@centos-8 ~]# cat /etc/systemd/system/take-user-input.service
[Unit]
Description=Get user input at boot stage
After=network.target
Before=sshd.service systemd-logind.service getty@tty1.service
[Service]
Type=oneshot
TTYPath=/dev/tty13
ExecStartPre=/usr/bin/chvt 13
ExecStart=/tmp/welcome.sh
ExecStartPost=/usr/bin/chvt 1
TimeoutStartSec=0
StandardInput=tty
TTYVHangup=yes
TTYVTDisallocate=yes
[Install]
WantedBy=default.target
RequiredBy=sshd.service systemd-logind.service getty@tty1.service
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
Here,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
After= If the script needs any other system facilities (networking, etc), modify the [Unit] section to include appropriate
After=, Wants=, or Requires= directives, as described in: man systemd.unit
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.
TTYPath= Specify a tty number here (the writer's choice of tty13 here was mostly arbitrary; however, keep in mind that
numbers higher than 12 require the chvt command to access them).
ExecStartPre=/usr/bin/chvt 13 This changes the physical console to tty13 (i.e., the tty specified with TTYPath=).
ExecStart= The full path to the main script, including any desired script arguments.
ExecStartPost=/usr/bin/chvt 1 This changes the physical console back to tty1 after the script finishes (this line
is not always necessary, e.g., if a display manager starts after the script, it will
probably steal focus by changing the physical console back to whichever tty it is running on).
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
StandardInput=tty This line is absolutely necessary; without specifying the value tty here, this setting defaults to null.
(Note that StandardOutput= and StandardError= can also be independently set;
however, by default they inherit their value from StandardInput=.)
For more information check man page of systemd.exec
Refresh the systemd configuration files
1
systemctl daemon-reload
Enable the service to automatically start at next boot
1
2
3
4
5
[root@centos-8 ~]# systemctl enable take-user-input.service
Created symlink /etc/systemd/system/default.target.wants/take-user-input.service → /etc/systemd/system/take-user-input.service.
Created symlink /etc/systemd/system/sshd.service.requires/take-user-input.service → /etc/systemd/system/take-user-input.service.
Created symlink /etc/systemd/system/systemd-logind.service.requires/take-user-input.service → /etc/systemd/system/take-user-input.service.
Created symlink /etc/systemd/system/getty@tty1.service.requires/take-user-input.service → /etc/systemd/system/take-user-input.service.
Now you are all done, proceed with the reboot of the Linux node.
Step 4: Verify the systemd unit file configuration
Post reboot connect to the GUI console of you Linux host, since I am using Oracle VirtualBox, I will connect to the console of my Virtual Machine.
Here as you see the booting has halted and is awaiting for user input from our script /tmp/welcome.sh
![[e22cf200da61550ffea6627dc7441ad6_MD5.webp]]
Once you give the input the booting of your Linux OS will continue.
As this stage we had explicitly used Before=sshd.service and After=network.target to execute script before activating sshd hence sshd will not be active at this stage although network should be active.
Lastly I hope the steps from the article to read user input during boot stage using systemd on CentOS/RHEL 7 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: read user input in shell script at boot stage in Linux. bash read input from stdin during boot up. take input at the startup script in Linux.
How to run script with systemd right before login prompt
In this article I will share example and sample systemd unit service file to run script with systemd right before login prompt in CentOS/RHEL 7/8 Linux. Using this systemd unit file you can run either some command or script as a last service on boot in Linux.
Ideally the last service we expect to be called on boot is the getty process which is responsible for showing the login prompt on the Linux console. So here our requirement is basically to execute script with systemd which should be called before getty process.
I will be using CentOS/RHEL 7/8 Linux node to verify the steps from this article to run script with systemd right before login prompt.
Step 1: Overview on systemd
If you are a beginner to systemd then I would recommend you to also readOverview on systemd and how it is different from legacy SysV scriptsbefore starting with this tutorial.
Step 2: Create Sample Script
Now to run script with systemd right before login prompt we need a script or command. For the sake of this article I have create a dummy shell script /tmp/script.sh which we will use for testing this article. I know the script is very dirty but let’s focus on the main agenda of this article as it serves the purpose.
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos-8 ~]# cat /tmp/script.sh
#!/bin/bash
# Run script with systemd right before login prompt
case $1 in
start)
systemctl list-jobs >> /tmp/file
echo "====================" >> /tmp/file
systemctl list-jobs | egrep -q 'getty.target.*start' && echo "starting script before login prompt" >> /tmp/file
exit 0
;;
esac
- The script once called will list the currently active jobs and targets. So with this command we will know the list of services and targets which are in the pipeline to be started or running.
- So if we see
getty.targetis planned to start then our script will echo “starting script before login prompt” into a temporary file/tmp/file - We have explicitly not added a stop function as that is not required for this article.
Provide executable permission to the script:
1
chmod a+x /tmp/script.sh
Step 3: Create unit file to run script with systemd right before login prompt
Now as highlighted under step 1, I have already written another article with the steps to create a new systemd unit file. Here we will name our systemd unit file as run-before-login-prompt.service under /etc/systemd/system. Below is the content of run-before-login-prompt.service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@centos-8 ~]# cat /etc/systemd/system/run-before-login-prompt.service
[Unit]
Description=Run script with systemd right before login prompt
After=systemd-user-sessions.service plymouth-quit-wait.service
After=rc-local.service
Before=getty.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/tmp/script.sh start
[Install]
WantedBy=multi-user.target
Here the main task is done by Before= and After= directives from systemd.unit
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
1
2
3
4
Before=, After=
These two settings expect a space-separated list of unit names. They configure ordering dependencies
between units. If a unit foo.service contains a setting Before=bar.service and both units are being
started, bar.service's start-up is delayed until foo.service has finished starting up.
Refresh the systemd configuration files
1
[root@centos-8 ~]# systemctl daemon-reload
Enable the service to automatically start at next boot
1
2
[root@centos-8 system]# systemctl enable run-before-login-prompt.service
Created symlink /etc/systemd/system/multi-user.target.wants/run-before-login-prompt.service → /etc/systemd/system/run-before-login-prompt.service.
Step 4: Verify the systemd unit file configuration
Now since we are done with the setting up of systemd. Let us verify our configuration. We will reboot our node and check the content of /tmp/file post reboot
1
2
3
4
[root@centos-8 ~]# reboot
login as: root
root@127.0.0.1's password:
Last login: Thu Jan 16 11:01:16 2020 from 10.0.2.2
Next verify the content of /tmp/file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@centos-8 ~]# cat /tmp/file
JOB UNIT TYPE STATE
259 tuned.service start running
232 NetworkManager-wait-online.service start running
236 vdo.service start running
231 network-online.target start waiting
129 multi-user.target start waiting
243 libvirtd.service start waiting
230 rpc-statd-notify.service start waiting
220 systemd-update-utmp-runlevel.service start waiting
265 getty.target start waiting
270 systemd-logind.service start running
218 run-before-login-prompt.service start running
217 kdump.service start waiting
279 rsyslog.service start waiting
274 filebeat.service start waiting
14 jobs listed.
====================
starting script before login prompt
So as expected we were able to run script with systemd right before login prompt. At this moment there were 14 jobs planned to start wherein couple of services were in running state including run-before-login-prompt.service and others. Since we had added a dependency of starting before getty.target our script was called before login prompt appeared (i.e. before getty.target entered running state)
NOTE
After boot, use systemd-analyze plot > file.svg to generate an image of the boot process for inspection. You can use any browser to view this file.svg and verify the boot process. There could be one or two short-lived services starting after run-before-login-prompt.service. If that’s a problem, modify /etc/systemd/system/run-before-login-prompt.service to set Type=idle
Lastly I hope the steps from the article to run script with systemd right before login prompt at boot up time on CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: How to execute script right before login prompt in CentOS/RHEL 7/8 Linux. How to execute a command or script before Linux boots up completely after reboot.
How to run script after N minutes of boot with systemd
In this article I will share systemd unit file and examples to run script after N minutes of boot using systemd (not with cron job). Ideally such task can also be done using cron jobs but since we already have systemd then why should we depend on cron job.
Using OnBootSec= or OnStartupSec= we can easily run script after N minutes of boot based on the value on N. let us verify this using some examples.
Overview on systemd.timer
- A unit configuration file whose name ends in “
.timer” encodes information about a timer controlled and supervised by systemd, for timer-based activation. - The common configuration items are configured in the generic “
[Unit]” and “[Install]” sections. The timer specific configuration options are configured in the “[Timer]” section. - For each timer file, a matching unit file must exist, describing the unit to activate when the timer elapses.
- By default, a service by the same name as the timer (except for the suffix) is activated. Example: a timer file foo.timer activates a matching service foo.service. The unit to activate may be controlled by
Unit= - Note that in case the unit to activate is already active at the time the timer elapses it is not restarted, but simply left running. There is no concept of spawning new service instances in this case.
- Due to this, services with
RemainAfterExit=set (which stay around continuously even after the service’s main process exited) are usually not suitable for activation via repetitive timers, as they will only be activated once, and then stay around forever. - Timer units automatically gain a Before= dependency on the service they are supposed to activate.
- Timer units will automatically have dependencies of type
Requires=andAfter=onsysinit.target, a dependency of typeBefore=on timers.target, as well asConflicts=andBefore=on shutdown.target to ensure that they are stopped cleanly prior to system shutdown.
To list all the available timers in your environment use
1
# systemctl list-timers
Step 1: Create sample script
To run script after N minutes of boot with systemd we will create a dummy script which will put some content in an empty file after 5 minutes of boot.
1
2
3
4
[root@centos-8 ~]# cat /tmp/delay_script.sh
#!/bin/bash
echo "Hello Deepak, I am running late" >> /tmp/file
Provide executable permission to the script
1
[root@centos-8 ~]# chmod u+x /tmp/delay_script.sh
Step 2: Sample systemd unit service file to run script after N minutes of boot
Here we must create a systemd unit service file and a matching systemd unit timer file to run script after N minutes of boot. We can either use OnBootSec= or OnStartupSec= to run script with delay after boot in Linux
Step 2.1: OnBootSec vs OnStartupSec
- OnBootSec= Defines a timer relative to when the machine was booted up. In containers, for the system manager instance, this is mapped to
OnStartupSec=, making both equivalent. - OnStartupSec= Defines a timer relative to when the service manager was first started. For system timer units this is very similar to
OnBootSec=as the system service manager is generally started very early at boot. It’s primarily useful when configured in units running in the per-user service manager, as the user service manager is generally started on first login only, not already during boot. ```shell [root@centos-8 ~]# cat /etc/systemd/system/run-script-with-delay.service [Unit] Description=Run script at startup
[Service] Type=oneshot ExecStart=/tmp/delay_script.sh TimeoutStartSec=0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
NOTE
You will end up with “`systemctl failing with unknown section Timer`” error if you put `[Timer]` section in .service unit file. `[Timer]` must be used only in `.timer` unit file
### Step 3: Sample systemd unit timer file to run script after N minutes of boot
**timer** is a unit configuration file whose name ends in “`.timer`” encodes information about a timer controlled and supervised by systemd, for timer-based activation.
```shell
[root@centos-8 ~]# cat /etc/systemd/system/run-script-with-delay.timer
[Unit]
Description="Run script after 5 minutes of boot"
[Timer]
OnBootSec=5min
[Install]
WantedBy=default.target
HINT
The unit to activate when this timer elapses is provided by using Unit= under [Timer]. Here since our systemd service and timer file are of same name i.e. run-script-with-delay, we have not defined any Unit= in the timer unit file. In case your unit service and timer file names are different then provide the mapped service file name with Unit= in the .timer file under [Timer].
Here for OnBootSec or OnStartupSec,
- The arguments to the directives are time spans configured in seconds. Example:
OnBootSec=50means 50s after boot-up. - The argument may also include time units. Example:
OnBootSec=5h 30minmeans 5 hours and 30 minutes after boot-up. - For details about the syntax of time spans supported with
OnBootSec=orOnStartupSec=follow man page of systemd.timer
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
Refresh the systemd configuration files
1
systemctl daemon-reload
Disable the systemd unit service file as this should not start automatically which is the idea behind this article. We want this service to run script after N minutes of boot based on the timer value.
1
2
[root@centos-8 ~]# systemctl disable run-script-with-delay.service
Removed /etc/systemd/system/default.target.wants/run-script-with-delay.service.
Next enable the systemd unit timer file so that this will run post boot and will then trigger the mapped systemd unit service file based on the timer value.
1
2
[root@centos-8 ~]# systemctl enable run-script-with-delay.timer
Created symlink /etc/systemd/system/default.target.wants/run-script-with-delay.timer → /etc/systemd/system/run-script-with-delay.timer.
Next reboot the node.
Step 4: Verify the systemd unit file configuration
Post reboot when we check the status of run-script-with-delay.timer, here observe the highlighted section where it shows the next trigger which is planned after 5 minutes which we have configured with OnBootSec in the timer unit file.
1
2
3
4
5
[root@centos-8 ~]# systemctl status run-script-with-delay.timer
● run-script-with-delay.timer - "Run script after 5 minutes of boot"
Loaded: loaded (/etc/systemd/system/run-script-with-delay.timer; enabled; vendor preset: disabled)
Active: active (waiting) since Thu 2020-01-16 14:34:34 IST; 27s ago
Trigger: Thu 2020-01-16 14:39:30 IST; 4min 27s left
Once the trigger time is hit, the service will perform it’s defined task which here is to run script after 5 minutes of boot. As you see now the trigger is showing “not applicable” for timer unit
1
2
3
4
5
6
7
[root@centos-8 ~]# systemctl status run-script-with-delay.timer
● run-script-with-delay.timer - "Run script after 5 minutes of boot"
Loaded: loaded (/etc/systemd/system/run-script-with-delay.timer; enabled; vendor preset: disabled)
Active: active (elapsed) since Thu 2020-01-16 14:34:34 IST; 5min ago
Trigger: n/a
Jan 16 14:34:34 centos-8.example.com systemd[1]: Started "Run script after 5 minutes of boot".
Also verify the content of our output file.
1
2
[root@centos-8 ~]# cat /tmp/file
Hello Deepak, I am running late
So as expected our script /tmp/delay_script.sh was called after 5 minutes of system boot without using any cron job.
Lastly I hope the steps from the article to run script after N minutes of boot without cronjob on CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: How to execute script with certain pre-defined delay after boot up in Linux. How to execute a script at startup with 5 minutes delay using systemd (not cronjob) in CentOS/RHEL 7/8 Linux. How to fix systemctl failing with unknown section ‘Timer’
How to run script with systemd at shutdown only (not at reboot)
I hope you are already familiar with systemd and the basic difference between SysV and systemd. Earlier I had written an article with examples to create your own systemd service unit file. Now let’s see how to run script with systemd at shutdown only. This script should not be called at reboot as ideally every script also gets called during reboot stage.
As a system administrator there may be a situation wherein you would want to run script at shutdown only and not at reboot. Such as performing some backup or any other task using a script or command at shutdown. We can also call a command using these steps to be called only at shutdown in Linux.
I have used CentOS/RHEL 7/8 Linux node to verify these steps to run script at shutdown only (not at reboot).
Step 1: Create a sample script
Now to run script at shutdown only with systemd we need a script. Below is a dummy script which will help us recognise if our script is getting called at reboot.target or shutdown.target. With systemctl list-jobs we know the currently active and running target. So the script should only work at shutdown.target or reboot.target
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos-8 ~]# cat /tmp/script.sh
#!/bin/bash
# Run script with systemd at shutdown only
case $1 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
I have also written a stop function but that anyhow will not be called but just to prove this fact this function is required. In such case only ExecStart will be called to run script with systemd at shutdown only and not at reboot
Step 2: Create unit file to run script with systemd at shutdown only
I have already written another article with the steps and examples to create a systemd service unit file. Here we will create our systemd unit file under /etc/systemd/system by the name myscript.service
Below is our systemd unit file which we will use to run script with systemd at shutdown only (not at reboot)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[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
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
Here from the man page of systemd.unit and systemd.service
- Conflicts If a unit has a
Conflicts=setting on another unit, starting the former will stop the latter and vice versa - Before= They configure ordering dependencies between units.
- Requires Configures requirement dependencies on other units. If this unit gets activated, the units listed here will be activated as well.
- Type Configures the process start-up type for this service unit. One of simple, forking, oneshot, dbus, notify or idle.
- ExecStart Commands with their arguments that are executed when this service is started.
- RemainAfterExit Takes a boolean value that specifies whether the service shall be considered active even when all its processes exited. Defaults to no.
Refresh the systemd configuration files
1
systemctl daemon-reload
Enable the script to automatically start at next boot
1
2
3
[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.
Step 3: Verify the systemd unit file configuration
Let us verify our systemd unit file. We will perform a shutdown of my CentOS/RHEL 7/8 Linux node to check if it run script with systemd at shutdown only and not at reboot.
1
shutdown now
After the node comes UP we check the content of our /tmp/file where we were writing our content from the dummy script
1
2
3
4
5
6
login as: root
root@127.0.0.1's password:
Last login: Tue Jan 14 22:41:22 2020 from 10.0.2.2
[root@centos-8 ~]# cat /tmp/file
starting shutdown
As expected the script was called at shutdown. Now let us do a reboot and check the same.
Before rebooting I will clean the content of /tmp/file
1
2
[root@centos-8 ~]# cat /tmp/file
[root@centos-8 ~]#
So as expected again the content of /tmp/file is empty so this script was not called at reboot.
Lastly I hope the steps from the article to run script with systemd at shutdown only and not at reboot on CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: How can I create a systemd service unit in CentOS/RHEL 7/8 that executes something only at shutdown time and not at reboot
How to run script on startup using systemd in Linux
How to execute a command or script with systemd at shutdown only and not at reboot in Linux In this article I will share a sample systemd unit file which you can use to run script at startup with systemd without using crontab in Linux.
There can be various scenarios when you expect a script or command to be called at startup such as
- Execute a script after waiting for N minutes of startup
- Execute a script after all the systemd services are loaded
- Execute a script immediately after login prompt appears
- Execute a script just before the login prompt appears
In this article I will cover below two topics as they are almost similar
- Run script at startup with systemd after network is reachable
- Execute script at starup after all the systemd services are loaded
I will be using CentOS/RHEL 7/8 Linux node to verify the steps from this article to run script with systemd right before login prompt.
Step 1: Overview on systemd
If you are a beginner to systemd then I would recommend you to also readOverview on systemd and how it is different from legacy SysV scriptsbefore starting with this tutorial.
Step 2: Create Sample Script
Now to run script at startup with systemd firstly we need a script or command. For the sake of this article I have create a dummy shell script /tmp/startup_script.sh which we will use for testing this article.
1
2
3
4
5
6
7
8
9
10
11
[root@centos-8 ~]# cat /tmp/startup_script.sh
#!/bin/bash
SCRIPT_NAME=$(basename -- "$0")
z=0
for i in {1..5}; do
sleep 1m
((z++))
wall $SCRIPT_NAME: finished minute ${z}
done
wall $SCRIPT_NAME: COMPLETELY FINISHED
This script will continue to run for 5 minutes and will print an echo statement on the screen every minute as a broadcast message using wall command for all Linux users on the respective node. And at the end of 5th minute it will print a completed broadcast. With this we can also make sure that the script is not killed by systemd if it continues to run for 5 minutes.
Provide executable permission to the script
1
chmod u+x /tmp/startup_script.sh
Create a new systemd service unit file with following content:
1
2
3
4
5
6
7
8
9
10
11
12
[root@centos-8 ~]# cat /etc/systemd/system/run-at-startup.service
[Unit]
Description=Run script at startup after network becomes reachable
[Service]
Type=simple
RemainAfterExit=yes
ExecStart=/tmp/startup_script.sh
TimeoutStartSec=0
[Install]
WantedBy=default.target
Next to activate the changes, execute following command:
1
systemctl daemon-reload
Enable the service to make sure this is called automatically after reboot
1
2
[root@centos-8 ~]# systemctl enable run-at-startup.service
Created symlink /etc/systemd/system/default.target.wants/run-at-startup.service → /etc/systemd/system/run-at-startup.service.
Step 3: Create systemd unit file for different scenario
Step 3.1: Run script at startup with systemd after network becomes reachable
In this scenario we will execute our script as soon as the network becomes reachable i.e. when network.target starts running during bootup stage by using After=network.target. The unit file should be located in either /usr/lib/systemd/system or /etc/systemd/system. I will place this under /etc/systemd/system as this is is used to place custom unit file.
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos-8 ~]# cat /etc/systemd/system/run-at-startup.service
[Unit]
Description=Run script at startup after network becomes reachable
After=network.target
[Service]
Type=simple
RemainAfterExit=yes
ExecStart=/tmp/startup_script.sh
TimeoutStartSec=0
[Install]
WantedBy=default.target
Step 3.2: Run script at startup with systemd after all systemd services are loaded
Now in this senario we must make sure all the systemd services for the respective target has loaded before starting the script. So to run script at startup with systemd after all systemd services are loaded we must defined our After= directive accordingly. Since the default.target will vary based on environment so rather than specifying specific target name we will use After=default.target so systemd will decide on it’s own the default.target and will call the script at startup in Linux.
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos-8 ~]# cat /etc/systemd/system/run-at-startup.service
[Unit]
Description=Run script at startup after all systemd services are loaded
After=default.target
[Service]
Type=simple
RemainAfterExit=yes
ExecStart=/tmp/startup_script.sh
TimeoutStartSec=0
[Install]
WantedBy=default.target
Step 3.3: Run script at startup with systemd after login prompt appears
Now in this scenario also we will only play around After= directive of the unit file. Now since the requirement is to run script at startup with systemd after login prompt appears then we will use After=getty.target
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos-8 ~]# cat /etc/systemd/system/run-at-startup.service
[Unit]
Description=Run script at startup after all systemd services are loaded
After=getty.target
[Service]
Type=simple
RemainAfterExit=yes
ExecStart=/tmp/startup_script.sh
TimeoutStartSec=0
[Install]
WantedBy=default.target
HINT
You can also create your own man page with a list of instructions for a script or a custom tool which you have created. In real time production environment it is always recommended to also create and release a man page for every script or tool we develop.
Here,
1
2
3
4
5
6
7
8
9
After= If the script needs any other system facilities (networking, etc), modify the [Unit] section to include appropriate
After=, Wants=, or Requires= directives, as described in: man systemd.unit
Type= Switch Type=simple for Type=idle in the [Service] section to delay execution of the script until all other
jobs are dispatched (see man systemd.service for even more choices -- e.g., Type=oneshot can be useful in concert with other services).
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.
Here if you observe we have defined After=network.target to make sure the script
Refresh the systemd configuration files and enable the service
1
2
systemctl daemon-reload
systemctl enable run-at-startup.service
Step 4: Verify the systemd unit file configuration
Now our configuration is in place to run script at startup in CentOS/RHEL 7/8 Linux.
HINT
You can also use systemctl list-jobs within the script to monitor the list of active jobs when the script was executed at startup.
Now post reboot of the Linux node we can see that our startup_script.sh is running in the background
1
2
3
[root@centos-8 ~]# ps -ef | grep startup
root 805 1 0 11:38 ? 00:00:00 /bin/bash /tmp/startup_script.sh
root 1198 1147 0 11:39 pts/0 00:00:00 grep --color=auto startup
Also in some time we start getting the broadcast messages from root user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Broadcast message from root@centos-8.example.com (somewhere) (Thu Jan 16 11:39:
startup_script.sh: finished minute 1
Broadcast message from root@centos-8.example.com (somewhere) (Thu Jan 16 11:40:
startup_script.sh: finished minute 2
Broadcast message from root@centos-8.example.com (somewhere) (Thu Jan 16 11:41:
startup_script.sh: finished minute 3
Broadcast message from root@centos-8.example.com (somewhere) (Thu Jan 16 11:42:
startup_script.sh: finished minute 4
Broadcast message from root@centos-8.example.com (somewhere) (Thu Jan 16 11:43:
startup_script.sh: finished minute 5
Broadcast message from root@centos-8.example.com (somewhere) (Thu Jan 16 11:43:
startup_script.sh: COMPLETELY FINISHED
I have verified the script for both scenarios to run script at startup with systemd (witout crontab) in Linux but I am not putting output from both scenarios as the output is same in both case.
NOTE
After boot, use systemd-analyze plot > file.svg to generate an image of the boot process for inspection. You can use any browser to view this file.svg and verify the boot process. There could be one or two short-lived services starting after run-at-startup.service. If that’s a problem, modify /etc/systemd/system/run-at-startup.service to set Type=idle
Lastly I hope the steps from the article to run script at startup with systemd without using crontab in CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Searches: How to execute script at startup as soon as network is reacable in Linux. How to call a script or execute command at Linux startup once the login prompt is visible in Linux. How to execute script with systemd at startup once all the systemd services are loaded in RHEL/CentOS 7/8 Linux with examples. How to run script at startup with crontab and cron job. how to add startup scripts in redhat linux 7. run script on startup.
