aptChecker - Part 2 - Remote Control M0YNG.uk

Created 2020-08-31

Modified 2021-02-10

Tagged

In part one I knocked up a thing to let me know when various things in my house needed updating. This works well as everything I wanted to keep an eye on is running Debian (or a variation of it) and is on the same network. But, what if I wanted to keep an eye on something not on the same network?

I could open the firewall so the remote system could directly POST updates, but that wouldn't be very secure, so I could add HTTPS but then I have to worry about certificates. I could get them to SSH info back, but then I have to worry about keys...

I ended up choosing to use SSH, and running commands on the remote system, this is fairly easy and I was already using key based authentication so didn't need extra setup. The only change needed was to allow the user to run apt update using sudo without a password.

This is simple, just add a line like this using visudo (possibly sudo visudo):

christopher ALL=(ALL) NOPASSWD:/usr/bin/apt update

That's it, all the setup needed on the remote system is done!

I then wrote a new script on myserver (on the internal network), called /etc/cron.daily/aptChecker-remote that looks like this:

#!/bin/bash

# this will run as root, so we need to use the correct ssh id
sshid="/home/christopher/.ssh/id_rsa"

# list of user+host combos to connect to
hosts=( "[email protected]" "[email protected]" "[email protected]" )

for host in "${hosts[@]}"
do
  echo ${host}
  # get fully qualified hostname
  hostname=$(ssh -i ${sshid} ${host} hostname -f)
  # run update
  ssh -i ${sshid} ${host} sudo apt update
  # count updates
  updatecount=$(ssh -i ${sshid} ${host} "apt list --upgradeable | wc -l")
  # correct for always getting at least one, even if there are none
  updatecount=$((updatecount - 1))
  echo $updatecount
  # get the current date+time
  datetime=$(date --iso-8601=seconds)
  # record the details
  curl -X POST -F "hostname=$hostname" -F "datetime=$datetime" -F "updatecount=$updatecount" http://myserver/aptCounter.php
done

I also updated the php that shows the results to tell me if the check was run today, or not:

$today = date('Y-m-d');
# ---
foreach ($aptCounterData as $host) {
  $host['goodbad'] = ($host['updatecount'] > 0 ? 'bad' : 'good');
  $host['updatedtoday'] = (strpos($host['datetime'], $today) === 0);
  echo "<tr><td>${host['hostname']}</td>";
  echo ($host['updatedtoday'] ? '<td class="good">today</td>' : "<td class='bad'>${host['datetime']}</td>");
  echo "<td class='${host['goodbad']}'>${host['updatecount']}</td></tr>";
}

Share this post on Mastodon