How to run scripts within a telnet session?

I want to connect to a remote host using telnet
there is no username/password verification
just

    telnet remotehost

then I need to input some commands for initialization

and then I need to repeat the following commands:

    cmd argument

argument is read from a local file, in this file there are many lines, each line is a argument
and after runing one "cmd argument", the remote host will output some results
it may output a line with string "OK"
or output many lines, one of which is with string "ERROR"
and I need to do something according to the results.

basically, the script is like:

    initialization_cmd  #some initial comands
    while read line
    do    
      cmd $line
      #here the remote host will output results, how can I put the results into a variable?
      # here I want to judge the results, like
      if $results contain "OK";then
           echo $line >>good_result_log
      else
           echo $line >> bad_result_log
      fi     
    done < local_file
    
     the good_result_log and bad_result_log are local files

is it possible or not? thanks!

You could try an expect script

Something like this should do it, command are in text file cmd_file in current directory output files are good_result_log and bad_result_log:

#!/usr/bin/expect -f
set timeout 2
spawn -noecho telnet remotehost
log_user 0
 
# Change command prompt to "PROMPT# " to make matching safer
send "PS1='PROMPT# '\r"
expect -re "PROMPT# '(.*)PROMPT# "
 
#Open Input and Output files
set cmds [open cmd_file r]
set eout [open bad_result_log w]
set gout [open good_result_log w]
 
while {[gets $cmds command] >= 0} {
    send "$command\r"
    expect -re "\r\n(.*)\r\n(.*)PROMPT# "
    set output $expect_out(1,string)
    if {[regexp {OK} $output match] == 1} {
       puts $gout $output
    } else {
       puts $eout $output
    }
}
 
close $cmds
close $eout
close $gout
 
send "exit\r"
expect eof