2016-02-11 110 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