集群环境下ShellScript批量进行ssh免密登陆的配置(公钥方式)

  • 安装expect
yum install -y expect
  • 使用的脚本 ssh_batch_conf.sh
#!/bin/bash

if [ $# -ne 2 ]; then
    echo "there are no enough arguments!"
    echo "Usage: $0 username password"
    exit 1
fi
# define account
username=$1
password=$2

# creating key-pair if there is not one
if [ ! -f $HOME/.ssh/id_rsa.pub ] ; then 
    ssh-keygen -t rsa -P '' -f $HOME/.ssh/id_rsa &>/dev/null 
    echo "---------- creating id_rsa.pub on local ----------"
    echo
fi

# get local ip list
# or using command "hostname -i"
ip_list=`ip a | grep -w inet | awk '{print $2}' | grep -P -o "\d+\.\d+\.\d+\.\d+" | xargs`
echo "---------- local ip: [$ip_list] ----------"
echo

# loading ip files and login
for ip in `cat ./host_ip.txt`; do
    if [[ $ip_list =~ $ip ]]; then
        continue
    fi
    echo "---------- copying $username public key to $ip ----------"    

/usr/bin/expect <<EOF
    # copying public key to target host
    spawn ssh-copy-id -i $HOME/.ssh/id_rsa.pub $username@$ip

    # input password via expect (automatically)
    expect {
        "yes/no" { send "yes\n"; exp_continue}
        "password" { send "$password\n"}
    }
    expect eof
EOF
    echo
done
echo "---------- finished ----------"
echo

注:ssh-copy-id 命令把公钥写入文件 .ssh/authorized_keys 时是追加 “ >> ”。

  • 存放ip的文件 host_ip.txt
192.168.74.201
192.168.74.202
192.168.74.203
192.168.74.204
192.168.74.205
  • 通过hostname登陆主机并将公钥添加到本地known_hosts文件。

脚本文件 addpubkey.sh

#!/bin/bash

if [ $# -lt 2 ]; then
	echo "Usage: $0 <width of number> <number of hosts>"
	echo -e "\033[31mwidth >= 2\033[0m"
	exit 1
fi

if [ $1 -lt 2 ]; then
	echo "Usage: $0 <width of number>"
	echo -e "\033[31mwidth >= 2\033[0m"
	exit 1
fi

width=$1
hosts_no=$2

echo "----- adding the node to the list of known hosts -----"
host=`hostname`
for i in $(seq $hosts_no) ; do
	str=`printf "node%0${width}d" $i`
	if [[ $str = $host ]] ; then
		continue
	fi
    echo "------ adding $str public key to local known_hosts ------"
/usr/bin/expect <<EOF
    spawn ssh $str hostname
    expect {
        "yes/no" { send "yes\n"}
    }
    expect eof
EOF
    echo
done
echo "---------- finished ----------"
echo
  • 接下来可以直接ssh登陆设备
ssh 192.168.74.204  #使用当前用户名登陆
或者
ssh bee@192.168.74.204
或者
ssh node03

登陆过程无需输入密码。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值