expect script - 如何将命令的输出拆分为多个变量

时间:2018-05-31 05:30:48

标签: expect

我正在尝试设置一个登录到远程服务器的expect脚本 获取最后创建的3个日志文件。输出(1行)如下所示:

root@server1:/cluster/storage/var/log/alarms$ 
Last 3 created files are:  FmAlarmLog_20180515_1.log FmAlarmLog_20180516_2.log FmAlarmLog_20180517_3.log

如何从此输出中拆分此输出并创建3个不同的变量(每个日志文件一个)? 日志文件的名称始终以" FmAlarmLog _"开头。

我需要稍后添加处理这些文件提取的部分。

#!/usr/bin/expect -f

set passwd "xxx"
set cmd1  "ls -ltr | tail -3 | awk '{print \$NF}'"
set dir "/cluster/storage/var/log/alarms"
set timeout 1
set prompt1 "*\$ "
log_user 0
spawn ssh admin@10.30.35.36
expect {
-re ".*Are.*.*yes.*no.*" {
send "yes\n"
exp_continue
}
"*?assword:*" {
send $passwd
send "\n"
}
}

expect  $prompt1  { send "cd $dir\r"}
expect  $prompt1  { send "$cmd1\r"}

set Last3LogFiles {}

expect \n
expect {

-re {^([^\r\n]*)\r\n} { 

    lappend Last3LogFiles $expect_out(1,string)
    exp_continue
 }
  -ex $prompt1
}

send_user "Last 3 created files are: $Last3LogFiles\n"

send "exit\n"
exit 0

1 个答案:

答案 0 :(得分:0)

试试这个:

expect  $prompt1  
send "$cmd1\r"

# express the prompt as a regular expression. 
# best practice is to match the prompt at the end of the current input,
# I don't know if you have a space at the end of your prompt

expect -re {(.*)\r\n\$ ?$}

# command output is in $expect_out(1,string)

set Last3LogFiles [regexp -inline -all {FmAlarmLog_\S+} $expect_out(1,string)]