Script which telnets to a device, runs commands and prints output to a file

I am connecting to a device using telnet, I want my script to perform certain commands : ie- show device , show inventory..etc and write the output it sees from the terminal to a file.
this is what I have got :

#!/usr/bin/expect -- 

set running 1 
spawn telnet <ip address> 
expect  {'^]'.} 
expect "login:"    
send "admin\r"    
expect "Password:"    
send "********\r"  


set fh [open master1.txt w]    
set fh1 [open master2.txt w]  
expect "master>" 
send "show device\r"  

while $running { 
expect {      
"\n" { puts $fh "$expect_out(buffer)"}      
eof {set running 0}          
timeout {set running 0}         
}         
} 


close $fh 
puts done  

expect "master>" 
send "show status\r"  
while $running { 
expect {      
"\n" { puts $fh1 "$expect_out(buffer)"}  
eof {set running 0}      
    timeout {set running 0}       
  }       
  } 
close $fh1 
puts done    

expect -re {# $}   
exit

So what is happening now is after the first loop it is printing the data of the result to master1.txt file...but after the execution it comes to:
master>
and stops.. I tried modifying the second loop to say:
expect "master>" send "exit\r"
just to see if it exits out but its not reading the command and not exiting, I have to manually exit out. Please help me on what I am doing wrong. This is my first time with "expect" so "expect-ing" to learn here :slight_smile:
Thanks..

You can put this statement at the top of your script so you can see what 'expect' is seeing:

exp_internal 1