期望命令并不总是将输出打印到文件

Expect command not always printing output to file

我有一个 main_parent_script.sh,我在里面调用另一个 parent_script.sh,它有以下命令:

/usr/bin/expect sftp_pass.sh list 22 sample_user hostname.hc.uk pass@123 get/FOR_20210420125933_NOTIFICATION_HEADER.json.zip > /temp/src_list.txt

每当我 运行 主父脚本时,它永远不会填充 src_list.txt 文件。但是当我单独 运行 sftp_pass.sh 命令时,它会使用以下 o/p:

正确填充 src_list.txt 文件
-rwxrwxrwx    0 300096102 300096102      576 May 24 15:04 get/FOR_20210420125933_NOTIFICATION_HEADER.json.zip
sftp> 

此外,我观察到 运行 时主父脚本的输出正确填充,仅当 ls 命令的输出提供 2 个或更多文件时。

下面是sftp_pass.sh脚本的内容:

log_user 0
##-------------Start of script----------------
set expectedcmd [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set host [lindex $argv 3]
set pass [lindex $argv 4]

if {$expectedcmd=="list"} {
set file [lindex $argv 5]
spawn sftp -oPort=$port $user@$host
expect "password:"
send "$pass\n"
set prompt "sftp>";
set command "ls -l $file";
}
##---------------------------------
expect "$prompt"    ;# wait for prompt
send   "$command\r" ;# send command
expect "$command\r" ;# discard command echo
log_user 1
sleep 5
expect -re "(.*)\r" ;# match and save the result
expect eof
send -- "exit\r"
##-------------End of script--------------------

我什至尝试使用 log_file 来输出脚本内部的执行。但我仍然遇到同样的问题。

这样试试:

...

expect "$command\r" ;# discard command echo
expect *
send_user -- $expect_out(buffer)
log_user 1
sleep 5
expect -re "(.*)\r" ;# match and save the result
expect eof

一些代码审查意见:

expect eof 应该是 after send exit -- 当前位置没有错误,只是你的脚本会“挂起”$timeout 秒等待sftp连接关闭,没看到,然后发送退出命令

如果第一个参数不是“列表”会怎样?您不会 spawn 任何进程,但会收到提示。

如果预期模式正确,您不需要sleep 5