Last active
February 5, 2021 18:13
-
-
Save n3s7or/725e51649bb38e68f7a499216ca89586 to your computer and use it in GitHub Desktop.
Simple bash script to check if a port is opened, and alert over Telegram if it is not.
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
#!/bin/bash | |
delay=10 | |
app=$0 | |
usage() { | |
printf "$app -h HOST -p PORT -i ID -t TOKEN | |
-i ID : 'chat_id' to send notification to | |
-t TOKEN : bot TOKEN to send notification from | |
ID and TOKEN are optional (for Telegram Notification)\n"; | |
exit 0; | |
} | |
alert() { | |
local data="{\"chat_id\": \"$id\", \"text\": \"$1\", \"parse_mode\": \"HTML\"}" | |
# Note here script doesn't care about result of the below command | |
# if for some reason it fails, you won't be notified over Telegram | |
local resp=$(curl -s -X POST \ | |
-H 'Content-Type: application/json' \ | |
-d "$data" \ | |
https://api.telegram.org/bot$token/sendMessage) | |
} | |
[ $# -eq 0 ] && usage | |
while getopts h:p:i:t: flag; do | |
case "${flag}" in | |
h)host=${OPTARG};; | |
p)port=${OPTARG};; | |
i)id=${OPTARG};; | |
t)token=${OPTARG};; | |
*)usage;; | |
esac | |
done | |
if [[ -z ${host+x} || -z ${port+x} ]]; then | |
printf "Must provide -h host and -p port\n" | |
usage | |
exit 0 | |
fi | |
if [[ -z ${id+x} || -z ${token+x} ]]; then | |
alert=0 | |
printf "Notification over telegram disabled\n" | |
else | |
alert=1 | |
fi | |
x=5 | |
while [[ $x -gt 0 ]]; do | |
res=$(nc -vz -w 5 $host $port 2>&1 ) | |
if [[ $res != *"succeeded"* && $res != *"open"* ]]; then | |
printf -- "$(date "+%d-%m-%y %T"): Test Failed\n%s\n" "$res" | |
(( x = x - 1 )) | |
if [[ $alert -eq 1 ]] | |
then | |
alert "<code>$res</code>" & | |
fi | |
else | |
printf "$(date "+%d-%m-%y %T"): Test Ok\n" | |
fi | |
if [[ $x -gt 0 ]]; then sleep $delay; fi | |
done | |
printf "$(date "+%d-%m-%y %T"): Failed 5 times, aborting.\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment