shell script/telnet - Remove/Control "Connection closed by foreign host"

How do I gain control of the "Connection closed by foreign host" message telnet yields when you connect to it in a shell script? I'm using the output:

#!/usr/local/bin/bash

count=$(ping -c 1 $1 | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ "$count" = "0" ]; then
    echo "$1 PING [FAILED]"
	else
	echo "$1 PING [OK]"
  fi
  
apache=`echo " " | telnet $1 80 | grep Connected | awk '{ print $1 }'`
  if [ "$apache" = "Connected" ]; then
    echo "$1 PORT 80 [OK]"
	else
    echo "$1 PORT 80 [FAILED]"
  fi
ssh=`echo " " | telnet $1 22 | grep Connected | awk '{ print $1 }'`
  if [ "$ssh" = "Connected" ]; then
    echo "$1 PORT 22 [OK]"
	else
    echo "$1 PORT 22 [FAILED]"
  fi
smtp=`echo " " | telnet $1 25 | grep Connected | awk '{ print $1 }'`
  if [ "$smtp" = "Connected" ]; then
    echo "$1 PORT 25 [OK]"
	else
    echo "$1 PORT 25 [FAILED]"
  fi
pop=`echo " " | telnet $1 110 | grep Connected | awk '{ print $1 }'`
  if [ "$pop" = "Connected" ]; then
    echo "$1 PORT 110 [OK]"
	else
    echo "$1 PORT 110 [FAILED]"
  fi
apache=`echo " " | telnet $1 80 | grep Connected | awk '{ print $1 }'`
echo " " | telnet $1 80 | grep Connected | awk '{ print $1 }'
++ echo ' '
++ telnet host.com 80
++ grep Connected
++ awk '{ print $1 }'
Connection closed by foreign host.
+ apache=Connected
  if [ "$apache" = "Connected" ]; then
    echo "$1 PORT 80 [OK]"
        else
    echo "$1 PORT 80 [FAILED]"
  fi
+ '[' Connected = Connected ']'
+ echo 'host.com PORT 80 [OK]'
host.com PORT 80 [OK]

But DeBug doesn't help me to understand why? :stuck_out_tongue:

I don't think that "ping" and "telnet" are suitable tools for port scanning .
You might allow such access on your own servers on your own LAN.
I would expect all such access to be blocked on a web server (with the possible exception of "ping").

Hi, phpfreak:

Telnet is probably spitting that out to standard error, which isn't caught by command substitutions and in your code isn't redirected nor piped. Try redirecting telnet's stderr to /dev/null.

telnet $1 80 2>/dev/null

If not for this script then for the future, it would likely benefit you to learn more about netcat (aka nc).

Regards,
Alister