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

相关推荐
杨云龙UP1 分钟前
2000—CentOS Linux 7上部署Oracle 19c(19.3) RAC(RedHat/CentOS 7/8)
linux·运维·服务器·数据库·oracle·centos
江湖有缘4 分钟前
可视化Docker资源清理方案:PruneMate容器化部署实战
运维·docker·容器
applebomb13 分钟前
最新的OPENWRT与FRPC不兼容问题
运维·服务器
逛逛GitHub18 分钟前
YC 总裁开源了自己亲手写的 AI Agent 大脑,1 周就 1 万点赞。
github
dovens24 分钟前
httpslocalhostindex 配置的nginx,一刷新就报404了
运维·nginx
适应规律1 小时前
Docker和虚拟机
运维·docker·容器
A-刘晨阳1 小时前
k8s之镜像拉取策略
运维·docker·容器·kubernetes·运维开发·harbor
IMPYLH1 小时前
【无标题】
linux·运维·服务器·网络·bash
比昨天多敲两行1 小时前
Linux权限管理
linux·运维·服务器
runningshark1 小时前
【Linux】VirtualBox ↔ Ubuntu+WinSCP 文件传输
linux·运维·ubuntu