使用expect工具实现远程批量修改服务器密码

使用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”

相关推荐
甲鱼92941 分钟前
MySQL 实战手记:日志管理与主从复制搭建全指南
运维
崔庆才丨静觅4 小时前
Claude Code GitHub Actions 使用教程
github·api·claude
砖厂小工1 天前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
程序员鱼皮1 天前
又一个新项目完结,我要出海了!
ai·github·开源项目
徐小夕1 天前
pxcharts-vue:一款专为 Vue3 打造的开源多维表格解决方案
前端·vue.js·github
Moment1 天前
想要长期陪伴你的助理?先从部署一个 OpenClaw 开始 😍😍😍
前端·后端·github
我叫黑大帅1 天前
前端如何利用 GitHub Actions 自动构建并发布到 GitHub Pages?
前端·面试·github
YuMiao1 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议