接著上篇,version1只是實現了簡單的功能,但是易用性還有待提高,我們來看看有什么可以改進的地方
可改進點
- version1實現的需要用戶輸入兩次密碼(scp和ssh),如何能在執行腳本的時候免交互
思路1:使用秘鑰文件
考慮過后不可行,因為此工具的目的就是安裝軟件,只需執行一次,如果用生成秘鑰文件的方式將會比version1更不好使用思路2:使用expect,可以不用多次輸入密碼靜默安裝,有關expect我的另一篇筆記有詳細記錄
expect:免交互自動化ssh
- 協程循環,用戶沒法退出,ctrl+c不友好
- 拆開,執行一次安裝一臺遠端機器
實現version2
有三個文件主入口文件remote_install.sh
和兩個被調用文件scp_expect.sh
install_expect.sh
version2使用expect實現了不用多次輸入的靜默安裝方式,但是執行expect需要執行機器先安裝expect,所以做了一點小兼容,如果機器裝了expect,則靜默安裝,如果機器沒裝expect靜默安裝失敗,則手動輸入密碼安裝
- 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執行失敗
cd mytestdir
if (( $? )); then rm * ; fi
可改進點
明文輸入密碼不夠安全,可參考如下方式解決輸入密碼界面不顯示問題
#!/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