I need to check if telnet is happening or not on multiple remote servers.
I wrote a while loop to SSH over multiple remote servers and triggers an email whenever the telnet fails. But the issue is while
loops iterates only over the first server and exits out of the script without reading remaining servers. Below is my shell script
#!bin/bash
while read host_details
do
USERNAME=$(echo $host_details | awk -F"|" '{print $1}')
HOSTIP=$(echo $host_details | awk -F"|" '{print $2}')
PORT=$(echo $host_details | awk -F"|" '{print $3}')
PROXY=$(echo $host_details | awk -F"|" '{print $4}')
PROXY_PORT=$(echo $host_details | awk -F"|" '{print $5}')
STATUS=$(ssh -n ${USERNAME}@${HOSTIP} -p${PORT} "timeout 4 bash -c \"</dev/tcp/${PROXY}/${PROXY_PORT}\"; echo $?;" < /dev/null)
if [ "$STATUS" -ne 0 ]
then
echo "Connection to $PROXY on port $PROXY_PORT failed"
mutt -s "Telnet connection to $PROXY on port $PROXY_PORT failed" [email protected]
else
echo "Connection to $PROXY on port $PROXY_PORT succeeded"
mutt -s "Telnet connection to $PROXY on port $PROXY_PORT succeeded" [email protected]
fi
done<.hostdetails
I observed my script works only when I remove IF
condition and my while
loops iterates over all the servers as expected.
Can anyone suggest why when I use IF
condition the script exits after first iteration? And how to make it work and get the email alerts?
Thanks to @GordonDavisson recommendation.
The mutt
in the script is treating the remaining server details as an input list, hence the script is getting terminated after reading the first server values.
Replace mutt
with another email program in your script. However, users who wish to go with mutt
, then it is recommended to add content to their email body or redirect the stdin from mutt to /dev/null
Below is the working solution:
#!bin/bash
while IFS="|" read -r userName hostIp Port Proxy proxyPort
do
STATUS=$(ssh -n -tt -o LogLevel=quiet ${userName}@${hostIp} -p${Port} 'timeout 4 /bin/bash -c' \'"</dev/tcp/${Proxy}/${proxyPort}"\'; echo $? < /dev/null | tr -d '\r')
if [ "$STATUS" -ne 0 ]
then
echo "Connection to $Proxy on port $proxyPort failed" | mutt -s "${hostIp}:Telnet connection to $Proxy on port $proxyPort failed" [email protected]
else
echo "Connection to $Proxy on port $proxyPort succeeded" | mutt -s "${hostIp}:Telnet connection to $Proxy on port $proxyPort succeeded" [email protected]
fi
done<.hostdetails
The trim command in the solution is to delete the carriage return(\r) I was getting in the variable(STATUS)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments