I have a bash script where I continuously read from a text file the hosts and port and create a connection to check for the status.
My code is:
while IFS=";" read -r host ports
do
eval "arr=($ports)"
for port in "${arr[@]}";
do
echo "connecting to $host on port $port" >> output.txt
timeout 5s telnet $host $port
exit_status=$?
if [[ $exit_status -eq 124 ]]; then
echo "$host on $port has timed out" >> output.txt
else
telnet $host $port >> output.txt
fi
echo "---------------------------------------------" >> output.txt
done
done < "$1"
The first if is to check if the connection timeouts.
That works as expected.
In the else - telnet $host $port, I am checking that if the connection does not timeout, then telnet into the remote host to see if the connection was successful or refused.
But, when the connection is successful, the script exits abruptly by spitting out:
Escape character is '^]'.
Connection closed by foreign host.
I want it to write to the output file, "connection is successful" and continue reading the remainder of $1.
When connection is refused, the script does not exit; it works as expected -- it continues to read from $1 and continues running the instructions.
I also, am in a situation where I cannot use netcat.
telnetconnection? Are you hoping to establish a connection and execute a command?telnet $host $port >> output.txt </dev/null?