前言
我的目标是建立一个脚本,可以在任何一台Centos7 linux系统上运行,并且无需交互就能让集群里面的机器实现无密码登录。
大概是这个样子。(所有cluster机器应该有相同的密码)
passwordless.sh 192.168.1.5,192.168.1.6,192.168.1.7 your-cluster-password
环境信息
软件版本
- 系统: CentOS 7.3.1611
- 软件: ssh-copy-id
- 软件: expect
拓扑信息
- Node1: 192.168.1.5
- Node2: 192.168.1.6
- Node3: 192.168.1.7
脚本代码
编写passwordless.sh脚本
touch passwordless.sh
chmod +x passwordless.sh
vi passwordless.sh
把下面代码复制到脚本中
#!/bin/bash
# Copyright 2018 Xiak.com.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################
# 脚本用法
# passwordless.sh 192.168.1.5,192.168.1.6,192.168.1.7 your-cluster-password
# 参数说明:
# 总共两个参数,参数之间用空格隔开
# 第一个参数定义了集群的IP地址,IP之间用逗号隔开
# 第二个参数为所有集群的密码
##########################################
# 脚本只要发生错误,就终止执行
set -o errexit
# 遇到不存在的变量就会报错,并停止执行
set -o nounset
# 只要一个子命令失败,整个管道命令就失败,脚本就会终止执行
set -o pipefail
# 工作目录
root_dir="/xiak/k8s"
# 生成的 cert 文件存放目录
cert_dir="$root_dir/cert"
hosts="${HOSTS:="${1}"}"
password="${2}"
# 工具 expect
if ! (hash expect) >/dev/null 2>&1; then
echo "=== expect command not found: Aborting ===" 1>&2
exit 2
fi
if ! (hash ssh-copy-id) >/dev/null 2>&1; then
echo "=== ssh-copy-id command not found: Aborting ===" 1>&2
exit 2
fi
##########################################
# Function: SshKeyGen()
# Usage: SshKeyGen
# Params: Null
# Comments: 生成 id_rsa id_rsa.pub
##########################################
SshKeyGen() {
# Delete old id_rsa
rm -f ~/.ssh/id_rsa
rm -f ~/.ssh/id_rsa.pub
# Generate new id_rsa.pub
expect -c "
set timeout -1;
spawn ssh-keygen -t rsa;
expect {
*/root/.ssh/id_rsa* {send -- \r;exp_continue;}
*passphrase):* {send -- \r;exp_continue;}
*again:* {send -- \r;exp_continue;}
eof {exit 0;}
};"
}
##########################################
# Function: SshKeyGen()
# Usage: SshKeyGen 192.168.1.2,192.168.1.3 password
# Params:
# $1 主机列表,主机之间以逗号分隔,不能有空格
# $2 主机的密码
# Comments:
# 1. 生成 id_rsa id_rsa.pub
# 2. 免密登录
##########################################
SshWithoutAuth() {
SshKeyGen
IFS=',' read -ra host_array <<< "${1}"
for host in "${host_array[@]}";
do
echo "ssh-copy-id to $host"
expect -c "set timeout -1;
spawn ssh-copy-id $host;
expect {
*(yes/no)* {send -- yes\r;exp_continue;}
*assword:* {send -- ${2}\r;exp_continue;}
eof {exit 0;}
}" >/dev/null 2>&1;
done
}
SshWithoutAuth ${hosts} ${password}
echo "All tasks done!"
脚本下载:
https://github.com/xiak/k8s-learning/tree/master/script