Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

send-mail-ip-address.sh (Source)

#!/bin/sh
# File: send-mail-ip-address.sh
# Startdate: 2021-05-17 08:59
#
# Purpose: send email message from newly build VM to myself with new hostname and IP address
# Usage:
#    send-mail-ip-address.sh
# Dependencies:
#    bgscripts-core (>=1.5.0)
test -z "${ADDRESS}" && export ADDRESS="${1}" # use ADDRESS environment variable or else use first parameter
test -z "${ADDRESS}" && export ADDRESS=bgstack15@gmail.com
test -z "${SERVER}" && export SERVER="$( hostname --fqdn )"
# Ensure PATH contains /sbin and /usr/sbin for ip and sendmail (called by send)
echo "${PATH}" | grep -qE '^\/usr\/sbin|:\/usr\/sbin' || export PATH="${PATH}:/usr/sbin"
echo "${PATH}" | grep -qE '^\/sbin|:\/sbin'           || export PATH="${PATH}:/sbin"
# Modified and improved from bgscripts framework.sh 2021-02-16a
thisip="$( ip -4 -o a s | awk '$1 !~ /^lo$/ && $2 !~ /^lo$/ && ($1 ~ /^e/ || $2 ~/^e/) {print $3,$4}' | awk -F'/' '{print $1}' | tr -dc '[0-9\.]' )"
# Send message
{
   echo "${SERVER} has IP address ${thisip}."
   echo "system finished build at $( TZ=UTC date "+%FT%TZ" )"
# leave cat INFILE unquoted in case it is inaccessible
} | send -f "root@${SERVER}" -h -s "${SERVER} is ${thisip}" "${ADDRESS}"