systemd – How can I make a screenshot log on Linux?


This solution uses ImageMagick‘s compare and import utilities.

As a normal user:

mkdir screenshot-log
vim screenshot.sh
mkdir -p ~/.config/systemd/user
vim ~/.config/systemd/user/screenshot.timer
vim ~/.config/systemd/user/screenshot.service
systemctl --user enable screenshot.timer
systemctl --user daemon-reload
systemctl --user start screenshot.timer
systemctl --user status screenshot.timer
systemctl --user list-timers

screenshot.sh:

#!/usr/bin/bash

DIR="/home/user/screenshot-log"
PREFIX="screenshot"
FORMAT="png"
PNSR_METRIC_DELETE_TRESHOLD=20
HTML_THUMB_WIDTH=200

DATE=`date +%Y-%m-%d__%H_%M_%S`
SCR_NEW="$DIR/$PREFIX-$DATE.$FORMAT"
SCR_LAST=`ls -t $DIR/$PREFIX* | head -1`

# do a screenshot
WINDOW_TITLE=`xdotool getactivewindow getwindowname`
import -window root $SCR_NEW

#requires ImageMagick
DISTANCE=`compare -metric PSNR $SCR_LAST $SCR_NEW /dev/null 2>&1`

if [ "$DISTANCE" = "inf" ]
then
  DISTANCE=1000
fi

IS_SIMILAR=`echo "$DISTANCE > $PNSR_METRIC_DELETE_TRESHOLD" | bc`
if [ "$IS_SIMILAR" = "1" ]
then
  rm $SCR_NEW
#  echo "`date` RM" >> $DIR/log-$PREFIX.log
else
  echo "<p>`date +%H:%M:%S` <a href="$SCR_NEW"><img width="$HTML_THUMB_WIDTH" src="$SCR_NEW" /></a> <br />$WINDOW_TITLE </p>" >> $DIR/`date +%Y-%m-%d`-$PREFIX.html
fi

~/.config/systemd/user/screenshot.timer:

[Unit]
Description=Take screenshot every 5 minutes with random delay

[Timer]
OnCalendar=*:00/5:00
RandomizedDelaySec=3m
AccuracySec=1s
Persistent=false

[Install]
WantedBy=graphical.target

~/.config/systemd/user/screenshot.service:

[Unit]
Description=Take screenshot
DefaultDependencies=no
After=local-fs.target time-set.target

[Service]
Type=oneshot
ExecStart=/home/user/screenshot.sh

[Install]
WantedBy=graphical.target