主要是ansible服务端需要将/root/.ssh/id_rsa.pub分发到其他服务器
ssh-keygen :这个命令是用来生成本机的公钥和私钥的
ssh-keyscan : 这条命令是用来把远程服务器的公钥来获取到本地的
1、创建密匙
ssh-keygen -t rsa
显示结果
[root@pokes01 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:V9/vMkTCJcnTI875fFApbpKdvwuE1SvLxI7p8dRpER0 root@pokes01
The key's randomart image is:
+---[RSA 2048]----+
| . o E.|
| *.=.+|
| +=Bo=.|
| +X*o.o|
| S ..oXo+.|
| . B B.=|
2、查看公钥
[root@pokes01 ~]# pwd
/root
[root@pokes01 ~]# cd .ssh/
[root@pokes01 .ssh]# ls
id_rsa id_rsa.pub
3、推送公钥
将公匙传送到客户端上
ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.17.0.102
ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.17.0.105
注意:同步过程需要输入yes和各自的root密码即可
4、测试免密登录
在用ssh直接登录下看看是不是不需要输入密码了
知道了怎么操作,这里给大家提供个脚本:
5、应用场景
在应用ansible的实际情况中,有一个很现实的问题,ansible是需要对主机做ssh免密登陆的,而挨个对主机做免密是非常的繁琐的,挨个敲IP不仅非常的繁琐而且容易出错,为解决这个问题,为以后使用ansible时的便捷,写了一个小脚本,实现批量对主机的免密配置:
#!/bin/bash
#在根目录下创建address文件,一行一个ip地址,将所有需要免密的主机ip填入
User=root #ssh免密的账户
passWord=123 #ssh免密主机的密码
address=`cat /address`
rpm -q sshpass &>/dev/null || yum -y install sshpass &>/dev/null #检测sshpass软件包是否安装
if [ $? -gt 0 ];then
YumBuild
yum -y install sshpass &>/dev/null || (echo "sshpass build error!" && exit)
fi
[ -d ~/.ssh ] || mkdir ~/.ssh;chmod 700 ~/.ssh
echo "正在创建密钥对...."
rm -rf ~/.ssh/id_rsa ~/.ssh/id_rsa.pub #创建密钥文件
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P "" &>/dev/null
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys
for ip in $address #调用/address的相关的ip信息进行ping测试,不通则跳过,通则对主机进行免密配置
do
ping $ip -c1 &>/dev/null
if [ $? -gt 0 ];then
echo "$ip无法ping通请检查网络"
continue
fi
sshpass -p "$passWord" ssh-copy-id -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no ${User}@$ip &>/dev/null
echo "$ip 密钥分发成功"
done
脚本小结:
需要注意的是,对第一次免密配置失败的主机,不可再用此脚本进行第二次配置,否则第一次配置成功的机器会失效,可以将脚本中创建密钥的部分注释,然后进行配置,最后,需要注意的是,脚本调用的IP地址的信息来自于/address文件中的信息,脚本中并没有写出判断,想来能应用ansible的必不会是新手,这种低级错误应该不会发生。
6、批量免密授权
1)、前提条件
操作前必须先配置好主机清单
ansible的inventory(即ansible的hosts)中配置:
[web]
10.0.0.20
10.0.0.31
2)、创建ssh秘钥
(1) 安装ssh非交互工具sshpass
yum -y install sshpass
3)、生成公钥
ssh-keygen -t rsa
4)、 批量复制秘钥并授权
ansible web -m shell -a 'mkdir ~/.ssh' -k
ansible web -m copy -a 'src=~/.ssh/id_rsa.pub dest=~/.ssh/authorized_keys mode=0600' -k
5)、 测试
ssh 10.0.0.20
ssh 10.0.0.21
6)、问题
[root@ansible-10 ansible]# ansible web -m ping -k
SSH password:
10.0.0.21 | FAILED! => {
"msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"
}
10.0.0.20 | FAILED! => {
"msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"
}
解决方法:
yum install epel-release -y
yum install sshpass -y