2016-02-11 109 views
0

我有以下脚本:if语句,不工作

#!/bin/bash 

pw=$1 
pw2=$2 
file=$3 
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 [email protected]* 
           send ena\r 
           expect "Password:" 
           send $pw2\r 
           expect "[email protected]*" 
           send skip-page-display\r 
           expect [email protected]* 
           send "show running-config\r" 
           log_file "$ip.conf" 
           expect "[email protected]*" 
           send "exit\r" 
           expect "[email protected]*" 
           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-Statement来检查预期的结果。 在此先感谢您的帮助!

回答

1

您有条件地期望通过使用期望与几个模式/动作对不同的事情,并使用exp_continue。取而代之的

if { expect "Please Enter Password:" } { 
    send $pw\r } 
} elseif { expect "Please Enter Login Name:" } { 
    send $user\r 
    send $pw\r 
} 
expect [email protected]* 

做这个

expect { 
    "Please Enter Password:" { send $pw\r; exp_continue } 
    "Please Enter Login Name:" { send $user\r$pw\r; exp_continue } 
    [email protected]* 
} 

你有一个错误:elseif需要它和开括号之间的空间。是的,expect是未知的一个Tcl表达式(docs

send exit后,你应该expect eof

0

由于TCL reference documentation showsif需要一个表达式作为其条件。

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

expect "string"并不像由expr评价有效的表达式。

+0

感谢这个信息,但我怎样才能解决呢? – colttt