2011-07-25 144 views
2

粘貼下面是一個bash腳本,結合期望代碼,其中:錯誤在bash處理/ expect腳本

  • 通過ssh連接到遠程主機,收集文件並準備TGZ文件;
  • 將tgz文件從遠程主機複製到本地機器;
  • 再次通過ssh連接到遠程主機並刪除以前創建的tgz文件;
  • 最後,在本地機器上提取tgz文件。

一切正常,如果傳遞的參數是有效的(即$host$user$pass)。如果其中一個不正確,腳本會掛起。我想知道如果在用戶名(或密碼)不正確的情況下如何包含一些錯誤處理(例如,在$ cmd1中)來終止帶有消息的腳本?

在此先感謝任何指針。

#!/bin/bash 
prog=$(basename $0) 
NO_ARGS=0 
E_OPTERROR=85 

# Script invoked with no command-line args? 
if [ $# -eq "$NO_ARGS" ]; then 
    echo "Usage: $prog [-h host] [-u username] [-p password]" 
    echo "  $prog -help for help." 
    exit $E_OPTERROR 
fi 

showhelp() { 
    echo "Usage: $prog [-h host] [-u username] [-p password]" 
    echo " -h: host" 
    echo " -u: username" 
    echo " -p: password" 
    echo " -help: this help message" 
    exit 2 
} 

user="" 
host="" 
pass="" 
now=$(date +"%m-%d-%Y") 
dir="data_$now" 
file="data.tgz" 

while getopts "h:u:p:help" name; do 
    case $name in 
    h) 
     host=$OPTARG 
    ;; 
    u) 
     user=$OPTARG 
    ;; 
    p) 
     pass=$OPTARG 
    ;; 
    help) 
     showhelp $0 
    ;; 
    esac 
done 

if [ -d "$dir" ]; then 
    rm -R $dir 
    mkdir $dir 
else 
    mkdir $dir 
fi 

cmd1=$(expect << EOF 
spawn ssh [email protected]$host 
expect "password: " 
send "$pass\n" 
expect "$ " 
send "cd /tmp\n" 
expect "$ " 
send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n" 
expect "$ " 
send "logout" 
EOF) 

cmd2=$(expect << EOF 
spawn scp [email protected]$host:/tmp/$file $dir 
expect "password: " 
send "$pass\n" 
expect "$ " 
EOF) 

CMD3=$(expect << EOF 
spawn ssh [email protected]$host 
expect "password: " 
send "$pass\n" 
expect "$ " 
send "cd /tmp\n" 
expect "$ " 
send "rm $file\n" 
expect "$ " 
send "logout" 
EOF) 

echo "$cmd1" 
echo "$cmd2" 
echo "$cmd3" 
cd $dir 
tar -xzf $file 
rm $file 
count=$(ls -1 | wc -l | awk '{gsub(/^ +| +$/, "")}1') 
cd .. 
#clear 
echo "All done. Extracted $count *.net files." 
+1

除外?期望? –

+0

@Ignacio拼寫更正。感謝您的評論。 – Andrej

回答

2

expect命令可以基於不同的答案不同的動作。

例如,你可以定義$ CMD1這樣的:

cmd1=$(expect << EOF 
spawn ssh [email protected]$host 
expect "password: " 
send "$pass\n" 
expect { 
{ 
    "Permission denied, please try again." { 
     send_user "Wrong password" 
     exit 
    } 
    "$ " { 
     send "cd /tmp\n" 
     expect "$ " 
     send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n" 
     expect "$ " 
     send "logout" 
    } 
} 
EOF) 

如果提供的密碼不能正常工作,該腳本將退出並打印消息「密碼錯誤」。

對於更高級的用法,請看看手冊頁。這裏有幾個例子和許多其他選項。

+0

感謝您的解決方案。工作很好。 – Andrej

1
expect { 
{ 
    "Permission denied, please try again." { 
     send_user "Wrong password" 
     } 
    "$ " { 
     send "cd /tmp\n" 
     expect "$ " 
     send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n" 
     expect "$ " 
     send "logout" 
    } 

在這裏,當我們刪除命令退出,預計應打印「密碼錯誤」,比通過發送做下一部分「CD/tmp目錄\ n」 ....... 是不是正確?