1、ansible批量增加sshkey脚本
#!/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)
2、增加时,碰到异常IP无法发送密钥时处理:
ssh-keygen -f "~/.ssh/known_hosts" -R 192.168.1.8
删掉ssh生成的缓存
3、ansible实用命令
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" 远程拷贝文件到目标服务器的上面去
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" 卸载包
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"软链接
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"
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"
4、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' }