一、ansible批量增長sshkey腳本python
#!/usr/bin/python #coding=utf-8 import pexpect import sys import os #列表裏面寫入你要增長的服務器IP servers = [ 'xxxx@192.168.1.7', 'xxxx@192.168.1.11', 'ssss@192.168.1.3', ... 'xxxx@192.168.1.49']; def sendPublicKey(servers): for server in servers: child = pexpect.spawn("ssh-copy-id -i /root/.ssh/id_rsa.pub %s" %(server)) index = child.expect(["yes/no","password","exist",pexpect.exceptions.EOF,pexpect.TIMEOUT]) if index != 0 and index != 1: print("未向此服務器%s上傳公鑰" %(server)) child.close(force=True) else: print("開始上傳公鑰") child.sendline('yes') child.expect("password:") child.sendline('szprize2018') child.expect("added") print("上傳完畢") print print("所有上傳完畢!") sendPublicKey(servers)
二、增長時,碰到異常IP沒法發送密鑰時處理:web
ssh-keygen -f "~/.ssh/known_hosts" -R 192.168.1.8shell
刪掉ssh生成的緩存緩存
三、ansible實用命令bash
ansible經常使用的一些命令:服務器
ansible all -a "bash /mnt/script/push_svnup.sh"
ansible all -s -a "ls /usr/bin/reivew" 使用sudo命令
ansible all -m copy -a "src=/etc/ansible/hosts dest=/etc/ansible/hosts" 遠程拷貝文件到目標服務器的上面去ssh
yum模塊
ansible all -m yum -a "name=httpd state=latest" 升級httpd
ansible all -m yum -a "name=ntp state=installed" 安裝包
ansible all -m yum -a "name=ansible stare=absent" 卸載包svn
file模塊
ansible webserver -m file -a "dest=/usr/bin/review.sh mode=755 owner=root group=wwww" 更改文件狀態
ansible webservers -m file -a "dest=/a/b/c/d mode=755 owner=www group=www state=new" 新建文件夾
ansible webserver -m file -a "dest=/tmp/hosts state=absent" 刪除文件
ansible webserver -m file -a "src=/usr/bin/review.sh dest=/usr/bin/review mode=755 state=link"軟連接 spa
service模塊
肯定服務都是開啓的
#ansible all -m service -a "name=httpd state=started"
重啓服務
#ansibel all -m service -a "name=httpd state=restarted"
關閉服務
#ansible all -m service -a "name=httpd state=stoped"rest
user模塊
ansible all -m shell -a "echo 123456 |passwd --stdin root" 更換密碼
#ansible all -m user -a "name=test password=<abc>" 新建用戶跟密碼
#ansible all -m user -a "name=test state=absent"
四、paybook
實例:批量建立維護帳戶
# vi useradd.yml
---
- hosts: all
user: root
sudo: no
vars:
#password: python -c 'import crypt; print crypt.crypt("devops1232", "fanghanyun")'
user: fanghanyun
tasks:
- name: add user
action: user name={{ user }} password=faJxjj/6hKXPs update_password=always shell=/bin/bash home=/home/{{ user }}
tags:
#vi useradd.yml - hosts: all remote_user: root tasks: - name: change password for root shell: echo '{{ item.password }}' |passwd --stdin root when: ansible_eth0.ipv4.address == '{{ item.ip }}' with_items: - { ip: "ip1", password: 'password1' } - { ip: "ip2", password: 'password2' } - { ip: "ip3", password: 'password3' }