Skip to content

Instantly share code, notes, and snippets.

@jefft4
Last active April 19, 2023 17:33
Show Gist options
  • Save jefft4/42fd5941e1d6c2957b353ac5fc698bd7 to your computer and use it in GitHub Desktop.
Save jefft4/42fd5941e1d6c2957b353ac5fc698bd7 to your computer and use it in GitHub Desktop.
SMART disk self-test script
#!/bin/bash
#
###################################################################
#
# Run short SMART self-test on all drives and email the result.
# Populate DISKLIST with your drive devices (w/o the '/dev/' part)
# and MailTo, MailFrom, MailSubject with your email header info.
#
# Your system needs a mailer set up for this to work as-is.
# Home Assistant parts require a suitable MQTT sensor definition.
# BROKER is the MQTT broker's IP or FQDN
# IFACE is the interface IP of this host to use when connecting
# to the MQTT broker
# TOPIC is the MQTT message topic defined by your HA sensor.
#
###################################################################
#
# Jeff Thompson, March 2023
#
# Licence: Copy and adapt freely!
#
###################################################################
TMP=/tmp/disktests.$$
BROKER=mqtt.boolie.net
IFACE=192.168.11.16
MSG=/tmp/msg.$$
MQTEMP=/tmp/mqtt.$$
PARAM=$1
HOST=`hostname`
TOPIC="systems/$HOST"
[email protected]
[email protected]
MailSubject="SMART test results from $HOST"
DISKLIST="sda sdb sdc sdd sde sdf sdg nvme0 nvme1"
NASTY=0
if [ "$PARAM" == "" ]
then
PARAM="ALL"
fi
echo >$MSG
if [ "$PARAM" == "ALL" ]
then
# request short self-tests
for DISK in ${DISKLIST}
do
if [ -e /dev/${DISK} ]
then
/usr/sbin/smartctl -t short /dev/${DISK} >/dev/null 2>&1
fi
done
# test takes typically 2 mins; wait 3 mins to be sure
sleep 180
# check the results
for DISK in ${DISKLIST}
do
if [ -e /dev/${DISK} ]
then
RES=`/usr/sbin/smartctl -a /dev/${DISK} 2>/dev/null | grep "test result:" | sed "s/.*test result: //"`
if [ "$RES" == "PASSED" ]
then
echo "SMART: $DISK passed short self-test" >>$MSG
echo "{ \"${DISK}_smart_test\": \"Okay\" }" >$MQTEMP
elif [ "$RES" == ""]
then
echo "SMART: $DISK did not return a self-test result" >>$MSG
echo "{ \"${DISK}_smart_test\": \"Fail\" }" >$MQTEMP
NASTY=1
else
echo "SMART: $DISK did not pass short self-test. Result=$RES. Full result follows." >>$MSG
/usr/sbin/smartctl -a /dev/${DISK} >>$MSG 2>&1
echo "-------------------------------------------------------------------------" >>$MSG
echo "{ \"${DISK}_smart_test\": \"Fail\" }" >$MQTEMP
NASTY=1
fi
# send to HA (retain to avoid misleading 'unknown' values after restarts)
/usr/bin/mosquitto_pub -A $IFACE -h $BROKER -t $TOPIC -f $MQTEMP --retain
fi
done
fi
# send to email if there's anything to say
if [ $NASTY -eq 1 ]
then
mail -s "${MailSubject}" "${MailTo}" -r "${MailFrom}" <$MSG
fi
# tidy up
rm -f $MSG $TMP $MQTEMP
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment