使用expect工具实现远程批量修改服务器密码
linux服务器安装Expect工具
1、首先查看系统中是否有安装expect。
# whereis expect
2、Expect工具是依赖tcl的,需要先安装tcl
#wget https://sourceforge.net/projects/tcl/files/Tcl/8.4.19/tcl8.4.19-src.tar.gz
 #tar zxvf tcl8.4.19-src.tar.gz
 #cd tcl8.4.19/unix
 #./configure
 #make
 #make install
 
3、安装Expect工具
#wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz
 #tar zxvf expect5.45.tar.gz
 #cd expect5.45
 #./configure --with-tcl=/usr/local/lib --with-tclinclude=…/tcl8.4.19/generic
 #make
 #make install
 #ln -s /usr/local/bin/expect /usr/bin/expect
 
4、Expect简要介绍
spawn:启动进程,并跟踪后续交互信息
 expect: 内部命令expect,判断上次输出结果是否包含指定字符串,如果有则立即返回,否则就等待,超时后返回,只能捕捉由spawn启动的进程的输出expect。
 send:向进程发送字符串,模拟输入,该命令不能自动回车换行,换行一般要加\r。
 interact:执行完成后保存交互状态,把控制权交给控制台。
 set timeout 30:设置超时时间为30秒,默认超时时间为10秒,timeout -1 为永不超时。
远程批量修改服务器脚本
1、准备密码配置文件
配置文件serverspd.txt,每行格式为:IP:账号:原密码:新密码:root原密码:root新密码
 例:
 # ip:user:password:new_password:root_password:newroot_password
 192.168.1.100:testuser:Redhat#2025312:test123test!@#:Redhat#2025312:testRtest!@#
 192.168.1.101:testuser:Redhat#2025312:test123test!@#:Redhat#2025312:testRtest!@#
 
2、批量修改脚本
该脚本适合不能直接使用root登录服务器,需要先使用普通账号远程登录,再切换为root账号修改密码
 #!/bin/bash
 #定义配置文件,每行格式为:IP:账号:原密码:新密码:root原密码:root新密码
 CONFIG_FILE=“servers.txt”
 #读取配置文件
 while IFS=: read -r IP USER OLD_PASSWORD NEW_PASSWORD ROOTOLD_PASSWORD ROOTNEW_PASSWORD; do
 echo “Processing $IP…”
 # 使用普通账号登录并切换到root
 sshpass -p “$OLD_PASSWORD” ssh -p 9999 -o StrictHostKeyChecking=no “$USER@$IP” << EOF
 # 提权到root
 expect << EOD
 spawn su -
 expect “password:”
 send “$ROOTOLD_PASSWORD\r”
 expect “#”
 send “echo ‘$NEW_PASSWORD’ | passwd --stdin $USER\r”
 send “echo ‘$ROOTNEW_PASSWORD’ | passwd --stdin root\r”
 expect eof
 EOD
 EOF
 # 检查是否修改成功
 if [ $? -eq 0 ]; then
 echo “Password for $USER@$IP updated successfully.”
 else
 echo “Failed to update password for $USER@$IP.”
 fi
 done < “$CONFIG_FILE”
 
