How to capture expect output using spawn and sftp

2019-08-16 15:08发布

问题:

I am using expect to spawn a sftp session as follows:

(lots of code snipped for clarity, and yes I understand the risks...)

#!/opt/csw/bin/expect -f

<snip>

spawn sftp $user@$host 

set rez [connect $passw]
if { $rez == 0 } {
  send "cd $location\r"
  set timeout -1
  send "ls -l\r" 
  send "quit\r"
  expect eof
  exit 0
}
puts "\nError connecting to server: $host, user: $user and password: $passw!\n"
exit 1

This works just fine.

My specific question is how to I capture the results of the send "ls -l\r" command in a file.

回答1:

After you send "ls\r" you should expect something. After the expect statement, the variable $expect_out(0,string) will contain the output you want. You do have to parse out the actual command string and the subsequent prompt.. You'll be able to find some examples at http://docs.activestate.com/activetcl/8.5/expect4win/