ansible批量修改伺服器密碼

2022-05-31 16:45:05 字數 1963 閱讀 6954

看了一下網上**大多數是ansible-playbook實現的,需要寫乙個指令碼,或者手動傳遞變數進去。

以前用python tcp模組寫過客戶端主動上報修改密碼指令碼

今天寫乙個ansible主控客戶端修改密碼

shell版本

#!/bin/bash

#展示所有定義的主機

allhost=`egrep -v '^$|^#|^\[' /etc/ansible/hosts |awk -f ' ' ''`

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 ''")

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))

執行時候是這樣:需要手動輸入主機前面的數字

使用ansible批量管理遠端伺服器

本地需要管理遠端的一批伺服器,主要執行以下任務 1 將本地的檔案複製到遠端所有伺服器 2 需要在遠端伺服器中執行乙個個命令 使用copy模組,可以將本地檔案一鍵複製到遠端伺服器 a後跟上引數,引數中指定本地檔案和遠端路徑 ansible通過ssh登入到遠端伺服器後,並不執行.bash profile...

ansible playbook批量修改密碼

1.將伺服器ip寫到ansible hosts檔案中 2.實現免密登入伺服器 將ansible伺服器公鑰拷貝到目標伺服器使用者目錄下的.ssh authorized keys 手動連線一次或者自己寫指令碼 3.編寫playbook 批量修改多使用者密碼 hosts test gather facts...

伺服器免密登入

由於有多台伺服器,每次登入還需要 去找對應的伺服器位址,然後輸入密碼,為了避免麻煩,就使用了免密登入。普通登入方式 ssh p 22 root 120.79.155.201 每次登入還需要輸入密碼,比較麻煩 更換免密碼登入 本地操作 本地的公鑰位置 ssh id rsa.pub ssh目錄下建立乙個...