作者:用户19910071 | 来源:互联网 | 2023-10-13 09:57
实现背景运维开发管理人员,当项目开始进行集群管理,传统的场景下,批量申请机器,但是一些操作虽然可以借助第三方的批量执行任务完成设置免密的工作,但是对于k8s部署,Spar
实现背景
运维开发管理人员,当项目开始进行集群管理,传统的场景下,批量申请机器,但是一些操作虽然可以借助第三方的批量执行任务完成设置免密的工作,但是对于k8s部署,Spark集群的部署等等需要集群概念的架构体系中,我们往往需要快速地进行集群批量的自动化免密设置,对于新手往往需要学习成本,所以本文通过批量免密设置实现快速的批量设置。
项目设计
1 创建执行目录
mkdir /tmp/ClusterSsh
cd /tmp/ClusterSsh
2 执行参数配置
vi host
xx.xx.xx.xx
xx.xx.xx.xx
3 查看执行脚本
#!/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 yr">>$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 $PASSWORDr">>$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.
sh ssh_auth.sh root $(paasswd) host
4 依赖自行安装检查
需要提前安装expect进行设置的,因为不同操作系统配置方式并不相同,所以自行设置实现:
yum install expect -y
免密登录检查:
ssh root@xx.xx.xx.xx
说明:可以部署密码就可以登录就可以证明绵密设置成功!
每天一个小技巧,你get到了吗?