接著上篇蝉稳,version1只是實(shí)現(xiàn)了簡(jiǎn)單的功能抒蚜,但是易用性還有待提高,我們來看看有什么可以改進(jìn)的地方
可改進(jìn)點(diǎn)
- version1實(shí)現(xiàn)的需要用戶輸入兩次密碼(scp和ssh)耘戚,如何能在執(zhí)行腳本的時(shí)候免交互
思路1:使用秘鑰文件
考慮過后不可行嗡髓,因?yàn)榇斯ぞ叩哪康木褪前惭b軟件,只需執(zhí)行一次收津,如果用生成秘鑰文件的方式將會(huì)比version1更不好使用思路2:使用expect饿这,可以不用多次輸入密碼靜默安裝,有關(guān)expect我的另一篇筆記有詳細(xì)記錄
expect:免交互自動(dòng)化ssh
- 協(xié)程循環(huán)撞秋,用戶沒法退出长捧,ctrl+c不友好
- 拆開,執(zhí)行一次安裝一臺(tái)遠(yuǎn)端機(jī)器
實(shí)現(xiàn)version2
有三個(gè)文件主入口文件remote_install.sh
和兩個(gè)被調(diào)用文件scp_expect.sh
install_expect.sh
version2使用expect實(shí)現(xiàn)了不用多次輸入的靜默安裝方式吻贿,但是執(zhí)行expect需要執(zhí)行機(jī)器先安裝expect串结,所以做了一點(diǎn)小兼容,如果機(jī)器裝了expect舅列,則靜默安裝肌割,如果機(jī)器沒裝expect靜默安裝失敗,則手動(dòng)輸入密碼安裝
- remote_install.sh
#!/bin/bash
function help()
{
#usage
cat << HELP
------------------------------------------------------------------------------
please input 4 parameters in order:
1st: path of xxx package at local host,
2nd: ip of the host which xxx will install
3rd: root's paasword of the host you inputted just now(2nd parameter)
4th: param4
Example:
bash remote_install.sh /opt/test/xx.zip 192.168.0.2 YourPaasWord param4
HELP
}
function install()
{
#read -a array
array=($1 $2 $3 $4)
echo ${array[*]}
# copy package to remote host
expect scp_expect.sh ${array[0]} ${array[1]} ${array[2]}
# compatible , if there is no expect, input paasword manually
if (( $? ))
then
scp ${array[0]} root@${array[1]}:/
fi
echo "bash setup.sh -param ${array[3]}"
# install package
expect install_expect.sh ${array[1]} ${array[2]} ${array[3]}
# compatible , if there is no expect, input paasword manually
if (( $? ))
then
ssh root@${array[1]} "mkdir -p /opt/test && \
cd /opt/test && \
cp /xx-*.zip ./ && \
unzip xx-*.zip && \
cd /opt/test/bin && \
bash setup.sh -param ${array[3]} "
# bash setup.sh -param ${array[3]} >/dev/null 2>&1 &"
fi
}
#while [ 1 ]
#do
if [ $# != 4 ]
then
help
exit
fi
install $1 $2 $3 $4
sleep 1
#done
- scp_expect.sh
#!/usr/bin/expect
set timeout 30
set path [lindex $argv 0]
set hostname [lindex $argv 1]
set password [lindex $argv 2]
spawn scp $path root@$hostname:/
expect {
"(yes/no)?" {
send "yes\r"
expect "assword:"
send "$password\r"
}
"assword:" {send "$password\r"}
}
#interact
expect eof
exit
- install_expect.sh
#!/usr/bin/expect
set timeout 30
set hostname [lindex $argv 0]
set password [lindex $argv 1]
set param3 [lindex $argv 2]
spawn ssh root@$hostname "mkdir -p /opt/test && \
cd /opt/test && \
cp /xx-*.zip ./ && \
unzip xx-*.zip && \
cd /opt/test/bin && \
bash setup.sh -param $param3 "
expect "assword:"
send "$password\r"
expect {
"ename:" {
send "All\r"
expect eof
exit
}
timeout {exit}
eof {exit}
}
遇到的問題
- 如何判斷expect執(zhí)行失敗
cd mytestdir
if (( $? )); then rm * ; fi
可改進(jìn)點(diǎn)
明文輸入密碼不夠安全帐要,可參考如下方式解決輸入密碼界面不顯示問題
#!/bin/bash
echo -n "Please enter your password:"
stty -echo
read password
echo -e "\nyou password is:$password"
stty echo
Reference:
http://blog.csdn.net/wang7dao/article/details/7724917
http://blog.csdn.net/qingsong3333/article/details/77542921