Skip to content

Instantly share code, notes, and snippets.

@lucasaba
Created August 28, 2019 08:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasaba/90e9815cb07c66e2a425ba0804d16800 to your computer and use it in GitHub Desktop.
Save lucasaba/90e9815cb07c66e2a425ba0804d16800 to your computer and use it in GitHub Desktop.
A script that sends a telegram message when an ubuntu server needs update or reboot
#!/bin/bash
IFS=';' read updates security_updates < <(/usr/lib/update-notifier/apt-check 2>&1)
HOSTNAME=`hostname`
BOT_TOKEN='THISTOKENISFROMBOTFATHER'
# Numeric id of the chat to publish messages to
CHAT_ID=1234567890
if [ ! -f ".update-check-status" ] ; then
echo "0:0" > .update-check-status
fi
CONTROL="$updates:$security_updates"
HASCHANGED=false
ACTUALSTATE=`cat .update-check-status`
if [ "$ACTUALSTATE" != "$CONTROL" ]; then
HASCHANGED=true
echo $CONTROL > .update-check-status
fi
function send_message {
curl -s -X POST https://api.telegram.org/bot$BOT_TOKEN/sendMessage -d chat_id=$CHAT_ID -d text="$1" -d parse_mode="markdown" > /dev/null
}
if [ $updates -gt 0 ] || [ $security_updates -gt 0 ] ; then
if $HASCHANGED; then
send_message "There are *$updates* updates available for *$HOSTNAME* and *$security_updates* of them are security updates"
fi
fi
if [ -f /var/run/reboot-required ]; then
send_message "Reboot needed on *$HOSTNAME*"
fi
@lucasaba
Copy link
Author

The script uses /usr/lib/update-notifier/apt-check to check if new updates are available and saves the state in a hidden file (.update-check-status) in order to prevent repeating messages.

The script is than launched hourly with crontab.

To create the telegram bot, you can follow this article.

Needs curl to work properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment