Last active
March 22, 2020 10:58
-
-
Save pacmac/f0a584fa2535ad86670890ee1f2ebbaa to your computer and use it in GitHub Desktop.
get fastest host ping and only output if a host is faster than the one provided in $1
This file contains 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 | |
# pacmac - 2020-03-22 | |
# fast-ping list-of-hosts | current-host | |
# fast-ping "uk-berkshire-2-ca-version-2.expressnetw.com,uk-east-london-ca-version-2.expressnetw.com" "uk-east-london-ca-version-2.expressnetw.com" | |
# fast-ping "uk-berkshire-2-ca-version-2.expressnetw.com,uk-east-london-ca-version-2.expressnetw.com" | |
## Initial Defaults | |
Smallest=1000000 | |
Server="" | |
## Params | |
Tolerance=3 | |
Pings=5 | |
## Command Vars | |
hosts=$1; | |
host="$2" | |
## Main Ping Function | |
func_ping () { | |
PingMs1=`ping -c $Pings -q -i .2 $myHost 2>/dev/null | grep avg | awk -F'/' '{print $5}' | sed -e "s/ ms//"`; | |
PingMs=${PingMs1/./} | |
PingMs=$((PingMs / 1000)) | |
#echo "$myHost $PingMs" | |
} | |
## Get Current Host | |
func_host () { | |
_host=$(cat $output | tr -d "\n" | tr -d "\r") | |
host=$(echo $_host | awk '{print $2}') | |
# echo -e "CURRENT:\t$host" | |
} | |
## Get Current Host Ping | |
func_host_ping () { | |
myHost=$host; | |
func_ping; | |
Smallest=$PingMs; | |
Server=$host; | |
} | |
## Get Fastest Host ( in:myHost out:Server, Smallest ) | |
func_fastping () { | |
for myHost in $(echo $hosts | sed "s/,/ /g");do | |
func_ping; | |
## DEBUG | |
# echo -e "$PingMs\t\t$myHost" | |
if [ $PingMs -gt 0 ] && [ "$((Smallest - PingMs))" -gt $Tolerance ];then | |
Server=$myHost | |
Smallest=$PingMs | |
fi; | |
done | |
} | |
if [ -n "$host" ]; then | |
func_host_ping; | |
func_fastping; | |
## if host, then only reply if changed. | |
if [ "$Server" != "$host" ]; then | |
echo "$Server"; | |
fi | |
else | |
## reply with fastest | |
func_fastping; | |
echo "$Server" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment