【问题标题】:Expect command not always printing output to file期望命令并不总是将输出打印到文件
【发布时间】:2021-06-02 23:33:18
【问题描述】:

我有一个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 来输出脚本内的执行。但我仍然有同样的问题。

【问题讨论】:

  • 你没有显示 shell 脚本,所以我们无法知道为什么没有填充输出文件。

标签: bash unix tcl expect


【解决方案1】:

试试这样:

...

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

【讨论】:

    【解决方案2】:

    一些代码审查cmets:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2014-05-15
      • 2019-02-16
      • 2011-12-19
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多