1

我正在编写一个期望脚本,它将 ssh 到几个 IP 以测试它们的连接性。我想包含一个“puts”语句,将每个测试的结果写入调用脚本的机器上的文件中。尽管我认为我正在遵循将 put 写入文件的手册,但它只写入 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
4

2 回答 2

2

You're probable problem was that you were using double-quotes. Therefore you should escape the literal $ that will be passed to expect (ie. \$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
于 2012-10-24T16:14:22.260 回答
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
于 2012-10-24T16:09:33.597 回答