Part 3: Monitoring Package File Integrity

Intro

Last time I almost got a systemd timer to run my pacman file integrity check script, but the service failed while running via systemd. So did the mail service that was supposed to inform me of errors. However, the scripts were working from the command line.

It’s finally working from systemd! Now my package files will be monitored for changes.

I had to make a few simple changes, which will be obvious in the future!

  • use environment vars correctly, $HOME, not /home/$USER. Much embarrassment.

  • sleep after the mail command so the subprocess can finish. The exact cause/need for this still escapes me. I tried

mail &
wait $!

but the mail command still didn’t execute. Do I need to use nohup? Will it still be logged in the systemd journal?

  • remove the line user=nobody, so the mail service run as root as with the default systemd services, or set the proper permissions on the mail script (755 instead of 700)

The working service files and scripts are given in following sections.

If you want to use them, make sure to set the ExecStart paths and User in the service file, and that the $EMAIL environment variable is set for said user.

Email Service

cat /etc/systemd/system/status-email-jotham@.service

[Unit]
Description=status email for %I to jotham

[Service]
Type=oneshot
ExecStart=/home/joth/bin/systemd-email.sh jothamapaloo@gmail.com %i
Group=systemd-journal

Pacman -Qkk Timer Unit

cat /etc/systemd/system/pacqkk.timer

[Unit]
Description=Pacman -Qkk change observer

[Timer]
Persistent=True
OnCalendar=*-*-* 19:00:00
Unit=pacqkk.service

[Install]
WantedBy=timers.target

Pacman -Qkk Service Unit

cat /etc/systemd/system/pacqkk.service

[Unit]
Description=Pacman -Qkk change observer
OnFailure=status-email-jotham@%i.service

[Service]
Type=oneshot
ExecStart=/home/joth/bin/pacqkk_check.sh
User=joth

[Install]
WantedBy=multi-user.target

Pacman -Qkk Check Script

cat ~/bin/pacqkk_check.sh

#!/bin/bash

PDIR="${HOME}/.pacqkk/"
PFILE="qkk"

if [ ! -d "$PDIR" ] 
then
  mkdir $PDIR
fi

if [ -f "${PDIR}${PFILE}_a" ]
then
  b_exists=true
  mv "${PDIR}${PFILE}_a" "${PDIR}${PFILE}_b" 
fi

pacman -Qkk > "${PDIR}${PFILE}_a"

if [ b_exists ]
then
  # TODO: don't do anything unless diff is not empty
  # TODO: needs to run as su 
  diff --suppress-common-lines --side-by-side \
  "${PDIR}${PFILE}_a" "${PDIR}${PFILE}_b" | \
  mail -s "$HOST qkk diff" $EMAIL
  sleep 10
fi

exit 0

Systemd Email Script

cat ~/bin/systemd-email.sh

#!/bin/bash

/usr/bin/sendmail -t <<ERRMAIL
To: "$1"
From: systemd <"root@$HOST">
Subject: "$2"
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8

$(systemctl status --full "$2")
ERRMAIL

sleep 10s

Updated [2015-04-26 Sun]: changing the pacqkk service type to simple (the default) will wait until the process finishes. That should remove the need for the sleep 10s.

Go Top
comments powered by Disqus