ansible免密管理主机

第一种方法:利用ansible自带的密码认证参数

可以在/etc/ansible/hosts文件中,定义好密码即可,即可实现快速的认证,远程管理主机

参数

ansible_host 主机地址

ansible_port 端口,默认是22端口

ansible_user 认证的用户

ansible_ssh_pass 用户认证的密码

 使用hosts文件的参数形式,来实现ssh认证

1.修改hosts文件,在文件最底部加入你要管理的主机,并配置参数
[change]
192.168.200.5 ansible_user=root ansible_ssh_pass=123456
192.168.200.6 ansible_user=root ansible_ssh_pass=123456
2.此时可以不需要输入密码,即可自动ssh验证通过了
[root@m01 ~]# ansible change -m command -a "hostname"
192.168.200.5 | CHANGED | rc=0 >>
rsnc01
192.168.200.6 | CHANGED | rc=0 >>
nfs01

第二种方法:ssh密钥方式批量管理主机

编写公钥分发脚本

[root@m01 ~]# cat ssh_key_send.sh 
#!/bin/bash
rm -rf ~/.ssh/id_rsa*
ssh-keygen -f ~/.ssh/id_rsa -P "" >/dev/null 2>&1
#管理主机的密码
SSH_Pass=123456 
#公钥的位置
Key_Path=~/.ssh/id_rsa.pub
#5,6为ip地址第三个小数点之后的数字 
#192.168.200.$ip为被管理主机所在的网段
for ip in 5 6
do
     sshpass -p$SSH_Pass ssh-copy-id -i $Key_Path "-o StrictHostKeyChecking=no" 192.168.200.$ip
done

运行脚本

[root@m01 ~]# sh ssh_key_send.sh 
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -o ' StrictHostKeyChecking=no' '192.168.200.5'"
and check to make sure that only the key(s) you wanted were added.

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -o ' StrictHostKeyChecking=no' '192.168.200.6'"
and check to make sure that only the key(s) you wanted were added.

现在即可直接连接

[root@m01 ~]# ssh -o ' StrictHostKeyChecking=no' '192.168.200.5'
Last login: Mon Jun 26 09:07:28 2023 from 192.168.200.4
[root@rsnc01 ~]# exit
登出
Connection to 192.168.200.5 closed.
[root@m01 ~]# ssh -o ' StrictHostKeyChecking=no' '192.168.200.6'
Last login: Mon Jun 26 09:08:13 2023 from 192.168.200.4
[root@nfs01 ~]# exit
登出
Connection to 192.168.200.6 closed.

 现在修改ansible的hosts文件

[root@m01 ~]# tail -5 /etc/ansible/hosts
[change]
#192.168.200.5 ansible_user=root ansible_ssh_pass=123456
#192.168.200.6 ansible_user=root ansible_ssh_pass=123456
192.168.200.5
192.168.200.6

 尝试ansible执行命令,看是否免密执行

[root@m01 ~]# ansible change -m "command" -a "hostname"
192.168.200.6 | CHANGED | rc=0 >>
nfs01
192.168.200.5 | CHANGED | rc=0 >>
rsnc01

发现执行成功。 

总结:1.第二种比第一种安全性更高,万一ansible主机被攻破泄露,直接暴漏了被管理的主机root密码

2.第二种更适合多台主机时,只需要在脚本修改ip即可

你可能感兴趣的:(ansible,ansible)