ansible批量修改服务器密码

看了一下网上代码大多数是ansible-playbook实现的,需要写一个脚本,或者手动传递变量进去。

以前用python tcp模块写过客户端主动上报修改密码脚本

今天写一个ansible主控客户端修改密码

shell版本

#!/bin/bash
#展示所有定义的主机
allhost=`egrep -v '^$|^#|^[' /etc/ansible/hosts |awk -F ' ' '{print $1}'`
now=`date +'%Y-%m-%d %H:%M:%S'`
for ip in $allhost
do
        echo $ip
done

#选择主机
echo -e "33[33;5m-----------------------33[0m"
read -p "请输入以上其中一台主机:" host

#生成密码
passwd=`head /dev/urandom | tr -dc A-Za-z0-9 | head -c 15`

#把要修改的主机和密码保存
echo "$now $host $passwd" >> ~/script/passwd.txt
echo "主机:$host 密码:$passwd"

#python3加密sha512
newpass=`/usr/bin/python3 -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash('$passwd'))"`

#执行修改密码
ansible $host -m user -a "name=root password="$newpass" update_password=always"

  

运行时候是这样:需要手动输入主机

python版本

#-*- coding:utf-8 -*-
import os
from passlib.hash import sha512_crypt
import getpass
import random
import string
#获取所有主机
f=os.popen("grep -vE '^$|^#|^[' /etc/ansible/hosts |awk '{print $1}'")
host=list(f)
#显示主机
for index,element in enumerate(host):
    print(str(index)+':'+element)

def randpass(length=15):
    chars=string.ascii_letters+string.digits
    return ''.join([random.choice(chars) for i in range(length)])
#选择主机
choice=int(input('请选择主机,填写数字:'))
mechina=host[choice].strip()
#生成密码
mima=randpass()
sha512mima=sha512_crypt.using(rounds=5000).hash(mima)
print('
您选择的主机是:',mechina,'密码是:',mima,'
')
#调用ansible修改密码
os.system(("ansible %s -m user -a 'name=root password=%s update_password=always'") % (mechina,sha512mima))

  

运行时候是这样:需要手动输入主机前面的数字

原文地址:https://www.cnblogs.com/guoyabin/p/12098682.html