作者:鄧聰聰
檢視ansible配置檔案下的hosts的檔案
[[email protected] scripts]# cat /etc/ansible/hosts
[test]
172.16.16.7
172.16.16.8
[[email protected]-server scripts]#
1.生成秘鑰對
ssh-keygen -t dsa -f ~/.ssh/id_dsa -P '' -q #生産密鑰對,免互動,并安靜輸出
這個指令會産生一個公鑰(~/.ssh/id_dsa.pub)和密鑰(~/.ssh/id_dsa),
-t dsa:表示使用密鑰的加密類型,可以為'rsa'和'dsa'
-P '':表示不需要密碼登入
-f ~/.ssh/id_dsa:表示密鑰存放的路徑為${USER}/.ssh/id_dsa
ssh-copy-id -i ~/.ssh/id_dsa.pub [email protected],hostname #如果你是單台機器的話,可以使用這種方式把公鑰檔案傳遞到對方主機

//被控主機下的檔案資訊
2.使用ansible-playbook來生成推送ymal檔案,批量推送
這裡使用到了authoried_keys子產品,vi /opt/ssh_key.yaml
# Using alternate directory locations:
- hosts: test //可以是組也可以是全部
user: root //推送所使用的使用者
tasks:
- name: ssh-copy
authorized_key:
user=root
key="{{ lookup('file', '/root/.ssh/id_dsa.pub') }}"
3.測試
[[email protected] scripts]# ansible all -m command -a date
172.16.16.8 | SUCCESS | rc=0 >>
Mon Mar 4 22:24:56 EST 2019
172.16.16.7 | SUCCESS | rc=0 >>
Mon Mar 4 22:24:56 EST 2019
[[email protected]-server scripts]#
4.1ansible的各項指令參數的使用
1.service #管理的服務必須存在在/etc/init.d/下有的服務腳本
name=service name #服務的名稱
state=參數 #停止服務 服務狀态資訊為過去時 (stared/stoped/restarted/reloaded )
案例:ansible test -m service -a "name=crond state=restarted"
2.yum
name=name #指定安裝的軟體
state=installed #安裝
案例:ansible test -m yum -a "name=vim state=installed "
3.copy #将/etc/hosts 檔案 傳輸到各個伺服器送,src=檔案的源路徑,dest=檔案的目标路徑
案例:ansible test -m copy -a "src=/etc/hosts dest=/tmp/"
4.script #腳本子產品,在本地執行腳本時,将腳本中的内容傳輸到遠端節點上運作
案例:ansible all -m script -a "/root/ansible-server/scripts/batch_free.sh"
4.2.劇本格式示例
劇本的檢查 ansible-playbook --syntax-check name.ymal
劇本彩排 ansible-playbook -C name.ymal
# Using alternate directory locations:
- hosts: test //冒号後面跟參數必須有空格
user: root
tasks: //冒号後面沒有參數的時候可以省略掉空格
- name: ssh-copy //名稱,可以跟多個劇本
authorized_key:
user=root
key="{{ lookup('file', '/root/.ssh/id_dsa.pub') }}"
使用Ansible的user子產品批量修改遠端客戶機的使用者密碼
[[email protected] ~]# vi /opt/root_passwd.yaml
---
- hosts: test
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: '123456' }
- { name: 'test', chpass: '123456' }
注意上面在yaml檔案中修改了遠端客戶機的root使用者密碼, test使用者密碼.
如果還想要修改其他使用者密碼, 則繼續按照上面規則添加即可!
轉載于:https://www.cnblogs.com/dengcongcong/p/10475580.html