命令通过Expect发送两次

时间:2013-03-05 10:34:32

标签: unix expect

我编写了一个Expect脚本,该脚本登录到远程系统,按顺序执行某些命令并在日志文件中捕获输出。

除了我检查日志文件时,一些命令似乎被发送两次,使得下一个要发送的命令出现在前一个输出的中间,这一切都发生得很好。它还会在检测到提示时再次发送(这是正确的执行)。此外,在所有情况下都不会出现这个问题,这更令人费解。

我想补充一点,我已经定制了包含此“--->”的提示。这是为了更容易通过另一个脚本进行输出解析。

这是期望代码,

set prompt "(]|%|#|>|\\$)"

# go to bash shell
expect -re $prompt
send "/bin/bash\r"

# customize the prompt
expect -re $prompt
send "PS1=\"\\u@\\H ---> \"\r"

# set new prompt into variable
expect -re $prompt
set newPrompt " ---> "

# opens file containing command list
set commFile [open commands.txt]

# reads each line containing commands from file, stores it in "$theLine" variable and sends it.
while {[gets $commFile theLine] >= 0} { 
    expect "$newPrompt"
    send "$theLine\r"
}

close $commFile

这就是我输出的方式。

"prompt --->" command1
----output----
----output----
command2
----output----
----output----

"prompt --->" command2
----output----
----output----

希望你明白这一点。

我不明白这种行为,也无法在其他地方找到任何解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

存在一些逻辑问题:发送PS1=...后,您会发现旧的提示。然后在循环内部,您希望在发送另一个命令之前有新的提示。这有帮助吗?

send "PS1=\"\\u@\\H ---> \"\r"
set newPrompt { ---> $}
expect -re $newprompt
set commFile [open commands.txt]
while {[gets $commFile theLine] >= 0} { 
    send "$theLine\r"
    expect -re "$newPrompt"
}