Reputation: 2466
I am trying to write an expect script in Linux which needs to do following job.
In step 1, I am trying to send one command to check if file exist but it does not work
log_user 1
spawn ssh -o "StrictHostKeyChecking=no" $username@$hostname
expect {
..... user and password checks
.....
send "IF EXIST C:\\path\\to\\file\\temp.zip (echo FOUND) else (echo NOTFOUND)\r"
expect "path" {
set result $expect_out(buffer)
puts $result
if{$result=="FOUND"} {
#compare with temp2.zip here
}
}
The result always contain the command I am sending not the output FOUND or NOTFOUND. Can someone let me know what I am doing wrong here?
Upvotes: 1
Views: 1258
Reputation: 4050
Instead of using pattern matching your script tries to process the buffer manually but makes the incorrect assumption that the buffer will only contain the text "(NOT)FOUND". The buffer will actually contain everything received since the last time the command expect
was used. Even if it did match the buffer correctly (e.g., with string match *NOTFOUND* $result
), however, it would be affected by the echo problem: the strings "FOUND" and "NOTFOUND" are in the command you send, which is most likely echoed back to you by the SSH server.
The following modification of the script hacks around the echo problem by not sending the literal strings it expects.
It works for me with the Bitvise SSH Server on the Windows side.
log_user 1
spawn ssh -o "StrictHostKeyChecking=no" $username@$hostname
# Log in here.
send "set prefix=___\r" ;# Combat the echo problem.
send "IF EXIST C:\\path\\to\\file\\temp.zip (echo %prefix%FOUND) else (echo %prefix%NOTFOUND)\r"
expect {
___NOTFOUND {
error {file not found}
}
___FOUND {
send_user Found!\n
# Do things with the file.
}
}
Upvotes: 1