目的:通过主控制端用最简便的方式修改所有被控制端的root密码
服务器之间建立ssh公钥认证
1.主控端建立ssh密钥
- ssh-keygen -t rsa
2.将生成的id_rsa.pub文件发送到被控端.也可以用别的方法,方法太多,不一一列举.
- #!/bin/bash
- for IP in ip_list.txt
- do
- scp ~/.ssh/id_rsa.pub $IP:/home/
- done
3.进入被控端
- mkdir ~/.ssh
- cat /home/id_rsa.pub >> /root/.ssh/authorized_keys #将id_rsa.pub的内容追加到authorized_keys 中
运行修改密码脚本
- #!/bin/bash
- #filename: root_pwd.sh
- #Environment: Centos 5.6 32-bit
- #Author: maoxian
- #Blog: maoxian.blog.51cto.com
- #定义变量
- ip_list=`cat /root/change_pwd/ip_list.txt`
- #定义一个自动生成随机密码的函数.-----------------------
- function pwdgen {
- strUp="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- strLow="abcdefghijklmnopqrstuvwxyz"
- strNum="0123456789"
- passLen="8"
- while [ "${#pass}" -le "$passLen" ]
- do
- passUp="${strUp:$(($RANDOM%${#strUp})):1}"
- passLow="${strLow:$(($RANDOM%${#strLow})):1}"
- passNum="${strNum:$(($RANDOM%${#strNum})):1}"
- pass="$pass$passUp$passLow$passNum"
- done
- echo ${pass:0:$passLen}
- }
- #选择改密码的方式.-------------------------------------
- read -p "密码随机生成输入a 密码手动设置输入b: " fangshi
- if [ $fangshi = a ];then
- TMP_PWD=`pwdgen`
- elif [ $fangshi = b ]; then
- read -p "请输入您要设置的密码: " TMP_PWD
- else
- echo " 输入错误 "
- exit
- fi
- #密码修改执行.-----------------------------------------
- for IP in $ip_list; do
- echo $TMP_PWD > TMP_PWD.txt
- ssh $IP passwd root --stdin < TMP_PWD.txt
- if [ $? = 0 ] ; then
- echo -e "$(date "+%Y-%m-%d %H:%M:%S")\t${IP}\t${TMP_PWD}\t" >> pwd_$(date +%Y-%m-%d).log
- else
- echo -e "$(date "+%Y-%m-%d %H:%M:%S")\t${IP} Password change fails\tplease check!\t" >> fails_$(date +%Y-%m-%d).log
- fi
- done
- rm -f TMP_PWD.txt
- echo "所有主机的密码修改已完成,请查看pwd_$(date +%Y-%m-%d).log文件!"
完了后会在当前目录下生成一个.log文件,把这文件保管好,最好是另外保存到安全的地方.密码忘记的时候还得看这个文件的,但又不能让别人看到.