how to close telnet from script dynamically



Hello,
I'm running through ksh the following telent command, the script
date.ksh should run between 4 to 6,7 minutes.
and I don't want to put sleep of 400, etc.
I can put in the end of the date.ksh an echo "DONE" or something...
but how can I get or license and not close the telnet session untill
it ended.
it's important because after the telnet end a ftp command should bring
the out files of the date.ksh back.

I'm not sure that ksh is strong enough to do it, any other script way
is wellcome... thanks

( sleep 2
echo "$USER"
sleep 2
echo "$PASSWORD"
sleep 2
echo "cd $REMOTE_DIR"
sleep 2
echo "gunzip file.tar.gz"
sleep 8
echo "tar xvf file.tar"
sleep 8
echo "./date.ksh"
) | telnet $HOSTNAME | grep "[-.:A-Z0-9a-z]\{1,250\},[-.:A-Z0-9a-z]
\{1,250\},"
.