if语句,不起作用

if statement, doesn't work

我有以下脚本:

#!/bin/bash

pw=
pw2=
file=
user="admin"

if [ $# -eq 0 ]
        then
                echo "bitte PW und IP-file als Parameter angeben"
fi


for ip in `cat $file`;
        do
                ping -c1 $ip >/dev/null 2>&1
                if [ $? -eq 0 ];  
                        then      
                                echo $ip
                                /usr/bin/expect <<EOD
                                spawn /usr/bin/telnet $ip
                                if { expect "Please Enter Password:" } {
                                        send $pw\r }
                                } elseif{ expect "Please Enter Login Name:" } {
                                        send $user\r
                                        send $pw\r }
                                expect telnet@*
                                send ena\r
                                expect "Password:"
                                send $pw2\r
                                expect "telnet@*"
                                send skip-page-display\r
                                expect telnet@*
                                send "show running-config\r"
                                log_file "$ip.conf"
                                expect "telnet@*"
                                send "exit\r"
                                expect "telnet@*"
                                send "exit\rn"
EOD                               
                else              
                        echo "$i nicht erreicht"
fi                                
done  

但是没有用,我收到以下错误:

spawn /usr/bin/telnet IP
invalid bareword "expect"
in expression " expect "Please Enter Passwor...";
should be "$expect" or "{expect}" or "expect(...)" or ...
    (parsing expression " expect "Please Enter ...")
    invoked from within
"if { expect "Please Enter Password:" } {
                                        send top_SECRET\r }"

有什么想法可以让它发挥作用吗? 有些交换机需要用户名,有些则不需要,所以我需要一个 If 语句来检查预期的内容。 在此先感谢您的帮助!

TCL reference documentation shows一样,if需要一个表达式作为其条件。

if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?

expect "string" 不是由 expr 评估的有效表达式。

您可以通过将 expect 与多个 pattern/acction 对一起使用来有条件地期望不同的东西,并使用 exp_continue。而不是

if { expect "Please Enter Password:" } {
    send $pw\r }
} elseif { expect "Please Enter Login Name:" } {
    send $user\r
    send $pw\r 
}
expect telnet@*

这样做

expect {
    "Please Enter Password:"   { send $pw\r; exp_continue }
    "Please Enter Login Name:" { send $user\r$pw\r; exp_continue }
    telnet@*
}

你有一个错误:elseif 需要在它和左大括号之间有一个 space。是的,expect 对于 Tcl 表达式 (docs)

是未知的

在你send exit之后,你应该expect eof