按照本文批量ssh之前需要满足一个前提:所有服务器用来ssh互信的账户和密码是一样的,不一样的改一下,后期再改回来
1、首先我们要安装一个自动化的集成套件,我们需要使用这个套件完成ssh批量免密
yum install -y expect
2、准备一个shell脚本,名字自定义我的叫ssh_all.sh
#!/bin/sh
DEST_USER=$1
PASSWORD=$2
HOSTS_FILE=$3
if [ $# -ne 3 ]; then
echo "Usage:"
echo "$0 remoteUser remotePassword hostsFile"
exit 1
fi
SSH_DIR=~/.ssh
SCRIPT_PREFIX=./tmp
echo ===========================
# 1. prepare directory .ssh
mkdir $SSH_DIR
chmod 700 $SSH_DIR
# 2. generat ssh key
TMP_SCRIPT=$SCRIPT_PREFIX.sh
echo "#!/usr/bin/expect">$TMP_SCRIPT
echo "spawn ssh-keygen -b 1024 -t rsa">>$TMP_SCRIPT
echo "expect *key*">>$TMP_SCRIPT
echo "send \r">>$TMP_SCRIPT
if [ -f $SSH_DIR/id_rsa ]; then
echo "expect *verwrite*">>$TMP_SCRIPT
echo "send y\r">>$TMP_SCRIPT
fi
echo "expect *passphrase*">>$TMP_SCRIPT
echo "send \r">>$TMP_SCRIPT
echo "expect *again:">>$TMP_SCRIPT
echo "send \r">>$TMP_SCRIPT
echo "interact">>$TMP_SCRIPT
chmod +x $TMP_SCRIPT
/usr/bin/expect $TMP_SCRIPT
rm $TMP_SCRIPT
# 3. generat file authorized_keys
cat $SSH_DIR/id_rsa.pub>>$SSH_DIR/authorized_keys
# 4. chmod 600 for file authorized_keys
chmod 600 $SSH_DIR/authorized_keys
echo ===========================
# 5. copy all files to other hosts
for ip in $(cat $HOSTS_FILE)
do
if [ "x$ip" != "x" ]; then
echo -------------------------
TMP_SCRIPT=${SCRIPT_PREFIX}.$ip.sh
# check known_hosts
val=`ssh-keygen -F $ip`
if [ "x$val" == "x" ]; then
echo "$ip not in $SSH_DIR/known_hosts, need to add"
val=`ssh-keyscan $ip 2>/dev/null`
if [ "x$val" == "x" ]; then
echo "ssh-keyscan $ip failed!"
else
echo $val>>$SSH_DIR/known_hosts
fi
fi
echo "copy $SSH_DIR to $ip"
echo "#!/usr/bin/expect">$TMP_SCRIPT
echo "spawn scp -r $SSH_DIR $DEST_USER@$ip:~/">>$TMP_SCRIPT
echo "expect *assword*">>$TMP_SCRIPT
echo "send $PASSWORD\r">>$TMP_SCRIPT
echo "interact">>$TMP_SCRIPT
chmod +x $TMP_SCRIPT
#echo "/usr/bin/expect $TMP_SCRIPT" >$TMP_SCRIPT.do
#sh $TMP_SCRIPT.do&
/usr/bin/expect $TMP_SCRIPT
rm $TMP_SCRIPT
echo "copy done."
fi
done
echo done.
3、准备集群ips文件,一行一个ip,如下
192.168.43.186
192.168.43.187
192.168.43.188
4、将shell脚本赋权
chmod 777 ssh_all.sh
5、运行,参数1是用来ssh的用户,参数2是该用户密码,参数3是集群ips文件
./ssh_all.sh root 123456 ./host_list
如果脚本运行正常会出现如下日志,注意我没有截全,最后会出现几个100%的进度条,之后用测试ssh效果就可以了
注意:你要用那个用户做服务器之间的SSH免密那就登录那个用户去操作,同时把上面所用的文件和文件夹都修改为所用用户所拥有,不然得话免密会出问题