SSH批量管理
expect自动交互
原创博文http://www.cnblogs.com/elvi/p/7662908.html
# SSH批量管理
# expect自动交互 #############################
#!/bin/sh
# 初次使用,以root批量执行 CMD=(
date
uname -r
hostname
) sh ${[*]} . /etc/init.d/functions
[[ -f /usr/bin/expect ]] || { echo "install expect";yum install expect -y; } #若没expect则安装
########## #############################
# #SSH批量执行shell命令
#!/bin/sh
. /etc/init.d/functions
[[ $# == ]] && { echo 'ege: /bin/sh '$' "命令1;命令2"';exit; }
for n in
do
echo
ssh -p22 192.168..$n $*
[[ $? == ]] && action "========IP:192.168.20.$n========" /bin/true || action "========IP:192.168.20.$n========" /bin/false
done
########## #############################
###批量推送文件
#!/bin/sh
. /etc/init.d/functions
[[ $# == ]] && { echo 'ege: /bin/sh '$' "本地文件" "(远程)目录"';exit; }
for n in
do
scp -P22 $ [email protected]..$n ~/ >/dev/null >& &&\
ssh -p22 -t [email protected]..$n sudo rsync ~/$ $ >/dev/null >&
[[ $? == ]] && action "========IP:192.168.20.$n" /bin/true || action "========IP:192.168.20.$n" /bin/false
done
########## #############################
#!/bin/sh
# 批量分发SSHKEY . /etc/init.d/functions
[[ -f /usr/bin/expect ]] || { echo "install expect";yum install expect -y; } #若没expect则安装 PUB=/`whoami`/.ssh/id_dsa.pub
[[ -f $PUB ]] || { ssh-keygen -t dsa -P '' -f /`whoami`/.ssh/id_dsa>/dev/null >&; } #若没公钥则生成 USER=sshync
PASS=sshync
# IP : SIP + SIP_end
SIP=192.168..
SIP_end=( ) #expect自动交互
function EXP() {
/usr/bin/expect << EOF
set timeout
spawn ssh-copy-id -i $PUB "-p22 $USER@$SIP$n"
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$PASS\n";exp_continue }
eof { exit }
}
EOF
}
#
[[ $ == y ]] || { echo -e 'ege: /bin/sh '$' y \n 当前'`whoami`'用户向远程用户'$USER'分发SSHKEY \n 远程主机列表'$SIP''${SIP_end[*]}' \n';exit; } for n in ${SIP_end[*]}
do
EXP |grep '.ssh/authorized_keys'>/dev/null >&
[[ $? == ]] && action "========IP:192.168.20.$n" /bin/true || action "========IP:192.168.20.$n" /bin/false
done #############################
#!/bin/sh
#Made by elven,
# MariaDB初始化,设置密码 DBPass=db2017
[[ -f /usr/bin/expect ]] || { echo "install expect";yum install expect -y; } #若没expect则安装
/usr/bin/expect << EOF
set timeout
spawn mysql_secure_installation
expect {
"enter for none" { send "\r"; exp_continue}
"Y/n" { send "Y\r" ; exp_continue}
"password:" { send "$DBPass\r"; exp_continue}
"new password:" { send "$DBPass\r"; exp_continue}
"Y/n" { send "Y\r" ; exp_continue}
eof { exit }
}
EOF
#测试
mysql -u root -p$DBPass -e "show databases;"
#############################