客戶要求每3個月修改一次主機密碼。密碼規則爲客服提供的一串字符 xxxx + 主機後3位。bash
ssh-keyscan 192.168.1.11 192.168.1.12 192.168.1.13 >> /root/.ssh/known_hosts
ssh-keygen -t rsa -P '' -f /root/.ssh/id_rsa
[zk] 192.168.1.11 ansible_ssh_pass=xxxx 192.168.1.12 ansible_ssh_pass=xxxx 192.168.1.13 ansible_ssh_pass=xxxx
--- - hosts: zk gather_facts: no tasks: - name: install ssh key authorized_key: user=root key="{{ lookup('file', '/root/.ssh/id_rsa.pub') }}" state=present
執行 playbook服務器
ansible-playbook ssh-addkey.yml
這時候去把 hosts 文件裏面的 ansible_ssh_pass 刪掉。 執行ansible all -m ping 也不須要密碼 此方案只適用於剛拿到的服務器,當你禁止root登陸之後,此方案失效。 解決方法是,使用普通用戶,賦予sudo權限ssh
客戶給的字符串爲 Rfv5%+,將該字符串及主機名後三位賦予xx變量spa
修改密碼腳本 pass_modify.shcode
#!/bin/bash xx=Rfv5%+`hostname|grep -oP '...$'` echo "$xx"|passwd --stdin root
使用 ansible script 模塊,遠程執行該腳本便可。ip
其他方法:字符串
--- - hosts: zk gather_facts: false tasks: - name: change user passwd user: name={{ item.name }} password={{ item.chpass | password_hash('sha512') }} update_password=always with_items: - { name: 'root', chpass: 'Lcsmy,123' }