Difference between revisions of "Systemd service file"
From Teknologisk videncenter
								
												
				m (→Copy files to destination)  | 
				m (→Enabling the service)  | 
				||
| Line 40: | Line 40: | ||
==Enabling the service==  | ==Enabling the service==  | ||
=== Copy files to destination===  | === Copy files to destination===  | ||
| − | Make sure your service and your service file are in the right destination.  | + | Make sure your service and your service-file are in the right destination.  | 
<source lang=bash>  | <source lang=bash>  | ||
sudo cp myserver-online.sh /usr/local/sbin  | sudo cp myserver-online.sh /usr/local/sbin  | ||
| Line 51: | Line 51: | ||
</source>  | </source>  | ||
=== Reload system file===  | === Reload system file===  | ||
| + | systemd reloads and hopefully finds your new service-file  | ||
<source lang=bash>  | <source lang=bash>  | ||
sudo systemctl daemon-reload  | sudo systemctl daemon-reload  | ||
</source>  | </source>  | ||
=== Verify files ===  | === Verify files ===  | ||
| − | systemd-analyze checks the   | + | systemd-analyze checks the service-file for errors. (Correct errors if any - remember to reload system files)  | 
<source lang=bash>  | <source lang=bash>  | ||
sudo systemd-analyze verify myserver-onlined.service  | sudo systemd-analyze verify myserver-onlined.service  | ||
</source>  | </source>  | ||
Revision as of 06:57, 17 April 2024
If i want a service daemon to log if my server is online every minute. The following procedure could be used:
Contents
My service
#!/bin/bash
# Filename: /usr/local/sbin/mysserver-online.sh
# Ownership: root:root 
# Permissions:  755 
IP="192.168.1.72"
LOGFILE="/tmp/myserver.log"
while :
do
        if ping -c 1 $IP > /dev/null 2>&1
        then
                echo "$(date) online" >> $LOGFILE
        else
                echo "$(date) OFFLINE" >> $LOGFILE
        fi
        sleep 60
done
My service file
# Filename: /lib/systemd/system/mysserver-onlined.service
# Owner: root:root
# Permissions: 644
[Unit]
Description=Test if my server online service
After=network.target
[Service]
ExecStart=/usr/local/sbin/mysserver-online.sh
Type=simple
Restart=always
[Install]
WantedBy=default.target
Enabling the service
Copy files to destination
Make sure your service and your service-file are in the right destination.
sudo cp myserver-online.sh /usr/local/sbin
sudo chown root:root /usr/local/sbin/myserver-online.sh
sudo chmod 755 /usr/local/sbin/myserver-online.sh
sudo cp myserver-onlined.service /lib/systemd/system
sudo chown root:root /lib/systemd/system/myserver-onlined.service
sudo chmod 644 /lib/systemd/system/myserver-onlined.service
Reload system file
systemd reloads and hopefully finds your new service-file
sudo systemctl daemon-reload
Verify files
systemd-analyze checks the service-file for errors. (Correct errors if any - remember to reload system files)
sudo systemd-analyze verify myserver-onlined.service