看了一下網上代碼大多數是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 "\033[33;5m-----------------------\033[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('\n您選擇的主機是:',mechina,'密碼是:',mima,'\n')
#調用ansible修改密碼
os.system(("ansible %s -m user -a 'name=root password=%s update_password=always'") % (mechina,sha512mima))
運行時候是這樣:需要手動輸入主機前面的數字

