期望把写入文件

时间:2012-10-24 15:18:21

标签: file bash expect channel puts

我正在编写一个期望脚本,它将ssh到几个IP来测试它们的连接性。我想包含一个“puts”语句,将每个测试的结果写入调用脚本的机器上的文件中。虽然我认为我正在遵循put写入文件的手册,但它只写入stdout。请参阅下面的脚本。最终结果是文件在本地计算机上创建,但没有输出指向它。相反,输出转到stdout。

#!/bin/bash

USER=user
PASSWORD=password
IPSTART=12.34.56.
OUTFILE="TEST.log"
PROMPT="#"

for IPEND in `seq 200 231`
do

expect -c "
        set timeout 3
        set chan [open $OUTFILE w]
        spawn ssh $USER@$IPSTART$IPEND
                expect -re \".*ssword.*\" {send \"$PASSWORD\n\"}

                expect {
                        -re \".*Are you sure you want to continue connecting.*\" {send \"yes\n\"; exp_continue}
                        -re \".*$PROMPT.*\$.*\"  {puts $chan \"$IPSTART$IPEND\n\"; send \"exit\n\"}
                }

        close $chan
"

done

我想知道引用是否存在问题,但我无法弄明白。

作为参考,这是来自http://www.tcl.tk/man/tcl8.4/TclCmd/puts.htm

的示例
set chan [open my.log a]
set timestamp [clock format [clock seconds]]
puts $chan "$timestamp - Hello, World!"
close $chan

2 个答案:

答案 0 :(得分:2)

你可能遇到的问题是你使用的是双引号。因此,您应该转义将传递给expect的文字$(即。\$chan):

#!/bin/bash

USER=user
PASSWORD=password
IPSTART=12.34.56.
OUTFILE="TEST.log"
PROMPT="#"

for IPEND in `seq 200 231`
do

expect -c "
        set timeout 3
        set chan [open $OUTFILE w]
        spawn ssh $USER@$IPSTART$IPEND
                expect -re \".*ssword.*\" {send \"$PASSWORD\n\"}

                expect {
                        -re \".*Are you sure you want to continue connecting.*\" {send \"yes\n\"; exp_continue}
                        -re \".*$PROMPT.*\$.*\"  {puts \$chan \"$IPSTART$IPEND\n\"; send \"exit\n\"}
                }

        close $chan
"

done

答案 1 :(得分:0)

好吧,我无法弄清楚如何在bash中这样做,所以我改变了整个脚本。它现在有效。

#!/bin/expect

set USER "user"
set PASSWORD "password"
set IPSTART "12.34.56."
set OUTFILE "TEST.log"
set PROMPT "#"
set CHAN [open $OUTFILE w]

for {set IPEND 200} {$IPEND <= 231} {incr IPEND} {
        spawn ssh $USER@$IPSTART$IPEND
                set timeout 3
                expect {
                        -re ".*ssword.*" {send "$PASSWORD\n"}
                        timeout {puts $CHAN "$IPSTART$IPEND does not work"}
                }

                expect {
                        -re ".*Are you sure you want to continue connecting.*" {send "yes\n"; exp_continue}
                        -re ".*$PROMPT.*\$.*"  {puts $CHAN "$IPSTART$IPEND works"; send "exit\n"}
                }
}

close $CHAN