51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

ansible免密登录ssh 实现步骤(实操)

ansible免密登录 {#articleContentId}

需求: 管理机 批量 推送到 被管理机

以root用户登录到主控端机器,ssh-keygen生成密钥对,通过ssh-copy-id 远程主机,将公钥拷贝到远程主机

ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.0.0.7

第一步:在管理机上取消 验证(不输入yes )

ssh-keygen 生成秘钥
vim /etc/ansible/ansible.cfg
host_key_checking = False

第2 步骤: 配置主机清单

第三步: 配置main.yml

ansible-galaxy init ssh

[root@m01 /etc/ansible/roles/ssh/tasks]#cat main.yml 
- name: Non secret authentication
  authorized_key: 
    user:root 
    key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"  
    state: present

第4步: 配置site

执行:

ansible-playbook  /etc/ansible/roles/site.yml

参考: ansible 免密登陆汇总


#####批量推送#######

批量推送公钥到远程机器

将以下文件命名为:push.ssh.ymal

  - hosts: tencent

    user: root

    tasks:

     - name: ssh-copy

       authorized_key: user=root key="{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"

       tags:

         - sshkey

执行推送命令

ansible-playbook ssh.ymal

方案2:

#!/bin/bash
rpm -q expect >/dev/null
if [ $? -ne 0 ]
then
  yum install -y expect &>/dev/null
fi

if [ ! -f /root/.ssh/id_rsa.pub ]
then
  /usr/bin/expect <<AAA
  set timeout 10  
  spawn ssh-keygen
  expect {
    "rsa):" { send "\r"; exp_continue }
    "passphrase):" { send "\r"; exp_continue }
    "again:" { send "\r" }
  }
  expect eof
AAA
fi

for i in {6,7,8,31,41,51}
do
/usr/bin/expect <<AAA
  set timeout 10 
  spawn ssh-copy-id 10.0.0.$i
  expect {
    "yes/no" { send "yes\r"; exp_continue }
    "password:" { send "1\r" }
  }
  expect eof
AAA

done
#####attention expect 里面是双引号

方案3:

#!/bin/bash

#变量优化
ROOT_PASS="1"
USER_NAME="root"
USER_PASS="1"
HOST_LIST="192.168.100.201 192.168.100.202 192.168.100.110 192.168.100.203"

#管理主机创建用户密钥对
su - $USER_NAME -c " cd /root && echo ""   | ssh-keygen -t rsa"
PUB_KEY="`cat /$USER_NAME/.ssh/id_rsa.pub`"

#利用ssh非免密环境在所有主机创建用户
for host in  $HOST_LIST; do
   sshpass -p$ROOT_PASS ssh -o StrictHostKeyChecking=no root@$host "useradd $USER_NAME"
   sshpass -p$ROOT_PASS ssh -o StrictHostKeyChecking=no root@$host "echo  "$USER_PASS" | passwd --stdin  $USER_NAME"
   sshpass -p$ROOT_PASS ssh -o StrictHostKeyChecking=no root@$host "mkdir -p  /$USER_NAME/.ssh"
   sshpass -p$ROOT_PASS ssh -o StrictHostKeyChecking=no root@$host "echo $PUB_KEY > /$USER_NAME/.ssh/authorized_keys"
   sshpass -p$ROOT_PASS ssh -o StrictHostKeyChecking=no root@$host "chmod 600 /$USER_NAME/.ssh/authorized_keys"
   sshpass -p$ROOT_PASS ssh -o StrictHostKeyChecking=no root@$host "chown -R $USER_NAME:$USER_NAME /$USER_NAME/.ssh"
done
#利用ssh非免密管理主机将公钥写入到所有主机authorized.keys
赞(6)
未经允许不得转载:工具盒子 » ansible免密登录ssh 实现步骤(实操)