场景:适合较大规模集群ssh互信配置.
1.配置节点1的/etc/hosts文件
2.在节点1新建2个脚本
3.配置节点1的环境变量
4.配置整个集群间的ssh互信
1.配置节点1的/etc/hosts文件
节点1编辑/etc/hosts文件,添加集群所有主机的IP地址和其对应的主机名:
vi /etc/hosts
192.168.56.102 JY-DB
192.168.56.103 JY-DB2
2.在节点1新建2个脚本
在节点1上传两个安装脚本到/usr/local/bin目录下。
脚本1:用来集群间同步拷贝文件。
cluster_copy_all_nodes
#!/bin/bash
SELF=`hostname`
if [ -z '$NODE_LIST' ]; then
echo
echo Error: NODE_LIST environment variable must be set in .bash_profile
exit 1
fi
for i in $NODE_LIST; do
if [ ! $i = $SELF ]; then
if [ $1 = '-r' ]; then
scp -oStrictHostKeyChecking=no -r $2 $i:$3
else
scp -oStrictHostKeyChecking=no $1 $i:$2
fi
fi
done
wait
脚本2:用来集群间同步运行命令。
cluster_run_all_nodes
#!/bin/bash
if [ -z '$NODE_LIST' ]; then
echo
echo Error: NODE_LIST environment variable must be set in .bash_profile
exit 1
fi
if [[ $1 = '--background' ]]; then
shift
for i in $NODE_LIST; do
ssh -oStrictHostKeyChecking=no -n $i '$@' &
done
else
for i in $NODE_LIST; do
ssh -oStrictHostKeyChecking=no $i '$@'
done
fi
wait
授予两个脚本的可执行权限:
chmod +x /usr/local/bin/cluster_*
3.配置节点1的环境变量
配置节点1的环境变量:
vi ~/.bash_profile
export NODE_LIST='JY-DB JY-DB2'
将集群中所有的主机名称列出,然后重新登录当前会话,或者执行下面命令使环境变量生效:
source ~/.bash_profile
4.配置整个集群间的ssh互信
4.1 各节点ssh-keygen生成RSA密钥和公钥
cluster_run_all_nodes 'hostname; ssh-keygen -q -t rsa -N \'\' -f ~/.ssh/id_rsa'
输出示例:
[root@JY-DB bin]# cluster_run_all_nodes 'hostname ; ssh-keygen -q -t rsa -N \'\' -f ~/.ssh/id_rsa'
root@jy-db's password:
JY-DB
root@jy-db2's password:
JY-DB2
如果配置有误,或者清除ssh互信的当前所有配置信息:
cluster_run_all_nodes 'hostname ; rm -rf ~/.ssh'
rm -rf ~/.ssh
4.2 将所有的公钥文件汇总到一个总的授权key文件中
在192.168.56.102执行汇总:
编辑脚本内容:
IP_NET='192.168.56.'
for((i=102;i<>
do
ssh $IP_NET$i cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
echo Summarize ssh info from $IP_NET$i into a single file.
done
注意:IP_NET是定义网段的变量,for循环包含了整个集群的IP范围,根据实际情况修改。
上述脚本内容是可以直接拷贝执行的,结果示例:
[root@JY-DB ~]# IP_NET='192.168.56.'
[root@JY-DB ~]# for((i=102;i<>
> do
> ssh $IP_NET$i cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
> echo Summarize ssh info from $IP_NET$i into a single file.
> done
root@192.168.56.102's password:
Summarize ssh info from 192.168.56.102 into a single file.
root@192.168.56.103's password:
Summarize ssh info from 192.168.56.103 into a single file.
出于安全性考虑,将这个授权key文件赋予600权限:
chmod 600 ~/.ssh/authorized_keys
4.3 将这个包含了所有互信机器认证key的认证文件,分发到各个机器中去
cluster_copy_all_nodes ~/.ssh/authorized_keys ~/.ssh/
4.4 验证ssh互信
节点1运行,都不输入密码返回主机名和时间即可:
cluster_run_all_nodes 'hostname;date'
至此,ssh集群间的互信已经配置完成。
但为了更加灵活的再其他节点也可以用到我们自定义的脚本,我们还可以做以下工作:
同步拷贝节点1的配置文件到其他节点:
cluster_copy_all_nodes ~/.bash_profile ~/
cluster_copy_all_nodes /etc/hosts /etc
cluster_copy_all_nodes /usr/local/bin/cluster_copy_all_nodes /usr/local/bin/
cluster_copy_all_nodes /usr/local/bin/cluster_run_all_nodes /usr/local/bin/
这时任意登录其他节点,也可以使用cluster_run_all_nodes验证ssh互信了:
cluster_run_all_nodes 'hostname;date'
联系客服