print to file

Posted by dmitsa on 2011-06-30 11:42

I need a short script to write remote directory contents to file. The script is -

package require Expect
set file_user [open "c:/Tcl/test/user.txt" "r"]
set user [gets $file_user line]
close $file_user
spawn telnet 192.168.1.200

expect {
"login:" {
send "$user\n"
}
default {
send_error "error in connection \n"
exit 2
}
}

expect {
"Password:" {
send "password\n"
}
default {
send_error "password error\n"
}
}
set file_printout [open "c:/tcl/test/printout.txt" "a"]
puts $file_printout [send "exec ls "]
close $file_printout

send exit
exit

The problem is printout.txt file is empty after script executin. Could you tell me where is my mistake ? Why I do not see any printout of ls into file ? Actually, I don't want to create any files on remote competer , I need to have the result of ls printout from remote computer into local's machine file/

?

jeffh
ActiveState Staff
Thu, 2011-06-30 13:10

Please reread the docs on expect. 'send' does not return the output of the result like some high-level 'rsh' call. You need to 'expect' the rest of the output and handle that data.

dmitsa | Sat, 2011-07-02 09:01

jeffh, thanks a lot for help, it was useful - log_file command is good solution for me. i've changed script such way

package require Expect

log_file -noappend "c:/Tcl/test/printout.txt"

spawn telnet 192.168.1.200

expect {
"login:" {
send "user\n"
}
}
expect {
"Password:" {
send "password\n"
}
}

expect "bash-2.05"
send "exec ls \r"

expect "bash-2.05"
send "exec ls -la\r"

puts "close connection"
send "exit\r"
log_file

exit

and see all printouts in log file

but i've encountered problem - after execution of this part of script
expect "bash-2.05"
send "exec ls \r"

i see,that script doesn't wait for next "expect "bash-2.05""
and I see -
"Connection to host lost" .
I can not understand what side release connection and why.

brevix | Wed, 2016-02-10 03:36

hi Dmitsa,

I am new to this

I have tried you method but the output file comes up blank. Any ideas?

Perhaps it is the security behind ssh...?

package require Expect

log_user 1
log_file -noappend ""

set login "user"
set password "xxxxx"
set host

spawn plink $host
expect "login as:"
send "$login\r"
expect "password:"
send "$password\r"

send "exec ls -la\r"
expect "~]$"

puts "close connection"
send "exit\r"
log_file

exit

I just get a blank file so it seems it is not logging the session. Any help would be appreciated.

Does using the following in the above circumstance make any difference

set filename [open a+]
expect "#"
exp_send "ls -la\r"
while 1 {
expect {
"\n" { puts $filename "$expect_out(buffer)"}
eof {set running 1}
timeout {set running 1}
}
}
close $filename
set timeout 30