Telnet Expect script question

Hi all,

I have written a small expect script which should spawn a telnet session login and execute some commands.

#!/usr/bin/expect -f

spawn telnet  $env(IP)
match_max 100000
expect "login:"
send -- "******\n"
expect -exact "Password:"
send -- "****\n"
expect "%"

Now I have got the following problem..................
If the telnet service is not running on the server, I would like to see the script to fail, but the script still carrys on to execute the commands, even it is not logged in?????
How can I stop this please?

---------- Post updated at 09:43 AM ---------- Previous update was at 05:55 AM ----------

Just in case someone else has the same problem.

I could sort it with

nc -w 5 -z ${MACHINE} 23
if [ $? -eq 0 ]
then
    echo "Telnet accepting connections"
else
    echo "Telnet connections not possible"
fi

How about:

catch {spawn -noecho telnet $env(IP)
set timeout 10
expect {
  timeout
    { send_user "Telnet timed out waiting for $env(IP)\n" ; exit }
  "onnection refused"
    { send_user "Connection was refused to $env(IP)\n" ; exit }
  "known host"
    { send_user "System $env(IP) is unknown\n" ; exit}
  "login:"
}
send -- "******\n"

Hi and thanks for the answere.

This works fine but you have missed of a close-brace at the top