主机列表文件hosts.txt示例,注意分隔符与脚本中的一致,本文选择分号“;”
192.168.2.41;userA
192.168.2.42;userA
192.168.2.43;userA
192.168.2.43;userB
脚本内容:
#!/bin/bash
remote_dir="/tmp"
remote_cmd="/usr/sbin/chpasswd -e < ${remote_dir}/chpass.txt;rm -f ${remote_dir}/chpass.txt"
>newpwd.txt
#读取文件中的行
#cat hosts.txt|while read LINE 此处如果用这种写法在ssh时会报错,引起循环中断
for LINE in `cat hosts.txt`
do
##################读取主机文件
#备份IFS
OLD_IFS="$IFS"
#设置新的分隔符为;
IFS=";"
arr=($LINE)
ip=${arr[0]}
usernm=${arr[1]}
#恢复IFS
IFS="$OLD_IFS"
##################获取随机密码
MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+="
LENGTH="9"
while [ "${n:=1}" -le "$LENGTH" ]
do
PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
let n+=1
done
n=1
##################生成密码文件和记录文件
secpw=`echo $PASS|xargs openssl passwd -1`
echo "${usernm}:${secpw}" >chpass.txt
echo "${ip};${usernm};${PASS}" >>newpwd.txt
PASS=""
# echo "${usernm}:${secpw}"
##################修改远程主机密码
sshpass -p abcd1234 scp -o StrictHostKeyChecking=no chpass.txt root@$ip:${remote_dir}
sshpass -p abcd1234 ssh -o StrictHostKeyChecking=no -t root@$ip "${remote_cmd}"
echo "..........${usernm}@${ip} password updated!"
done
>chpass.txt
echo "======done!!"