要定時把 CentOS 伺服器上的資料庫備份檔自動複製回本機,可善用 expect 腳本自動處理 scp 的密碼輸入環節。
腳本寫法如下,特別提醒 timeout 一定要設長一點,否則可能複製到一半就中斷:
#!/usr/bin/expect -f
set password ********
set date [exec date "+%Y%m%d"]
spawn scp -r root@{IP位址}:/home/{ps-name}/backup/db/production$date.sql /root/db/
set timeout 3
expect {
"yes/no" {send "yes\r"; exp_continue}
}
expect "root@{IP位址}'s password:"
set timeout 30
send "$password\r"
set timeout 3000
send "exit\r"
expect eof
關鍵在於:先以短 timeout 處理首次連線的 yes/no 確認,送出密碼後再把 timeout 拉長到足夠久(如 3000 秒),確保大型備份檔能完整下載,最後以 eof 收尾。