Last active
July 10, 2021 12:59
-
-
Save gtrabanco/d3c4214fe267609e6b6f59ff094cbdf6 to your computer and use it in GitHub Desktop.
Ping to HOST and if it fails return a message through Telegram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
#shellcheck disable=SC2034 | |
# | |
# CONFIG | |
# | |
# IP or HOSTNAME to ping | |
# IP o host al que hacer ping | |
# HOST="192.168.33.1" | |
# Message if fails | |
# Mensaje si falla | |
FAILURE_MESSAGE="Telegram PING to \`%s\` failed" | |
# Time between pings in secs | |
# Tiempo entre pings en segundos | |
PING_TIME=5 | |
# Number of tries | |
# Número de reintentos | |
PING_RETRIES=3 | |
# Telegram | |
# BOT_API_KEY="" | |
# BOT_CHAT_ID="" | |
# BOT_VIM_NAME="" | |
# Other | |
PATH_LOG="$HOME/telegram-ping.log" | |
CURRENT_DATE="$(date)" | |
PING_CMD=(ping -c 2 -i 5 -o) | |
_log() { | |
touch "$PATH_LOG" | |
if [[ -w "$PATH_LOG" ]] && [[ -t 0 ]]; then | |
[[ $# -gt 0 ]] && printf "%s\n" "$@" >> "$PATH_LOG" | |
elif [[ -w "$PATH_LOG" ]] && [[ ! -t 0 ]]; then | |
[[ $# -gt 0 ]] && echo "$*" >> "$PATH_LOG" | |
echo "$(< /dev/stdin)" >> "$PATH_LOG" | |
elif [[ -t 0 ]]; then | |
[[ $# -gt 0 ]] && printf "%s\n" "$@" | |
else | |
[[ $# -gt 0 ]] && echo "$*" | |
echo "$(< /dev/stdin)" | |
fi | |
} | |
# | |
# DO THE WORK | |
# | |
if [[ -z "${HOST:-}" || -z "${FAILURE_MESSAGE:-}" ]]; then | |
echo "Empty host or message" | _log "Configuration error" | |
else | |
RETRIES=0 | |
FAILED=true | |
while [[ $RETRIES -lt ${PING_RETRIES:-2} ]]; do | |
RETRIES=$(( RETRIES + 1 )) | |
_log "Ping retry $RETRIES to host: $HOST" | |
if "${PING_CMD[@]}" "$HOST" &>/dev/null; then | |
FAILED=false | |
break | |
fi | |
sleep "${PING_TIME}s" | |
done | |
if ${FAILED:-}; then | |
#shellcheck disable=SC2059 | |
message="$(printf "$FAILURE_MESSAGE" "$HOST")" | |
_log "Ping to \`$HOST\` failed" | |
data=$(curl --silent "https://api.telegram.org/bot${BOT_API_KEY}/sendMessage" --data-urlencode "chat_id=${BOT_CHAT_ID}" --data-urlencode "text=$message") | |
[[ $(echo "$data" | jq -r '.ok') != "true" ]] && _log "Fail to send telegram message" | |
else | |
_log "Ping to \`$HOST\` sucess" | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uncomment or comment the variables if you you want to have static values, if not, use ENV vars like: