批量修改root密码shell
2024-04-09 / shell / 184 次围观 / 0 次吐槽 /#!/bin/bash # 检查输入参数 if [ $# -ne 1 ]; then echo "Usage: $0 serverlist.txt" exit 1 fi # 检查脚本是否有执行权限 if [ ! -x "$(command -v sshpass)" ]; then echo "Error: sshpass is not installed or not executable. Please install it before proceeding." exit 1 fi SERVER_LIST_FILE="$1" ERROR_LOG="error.txt" # 创建错误日志文件(如果不存在) [ ! -f "$ERROR_LOG" ] && touch "$ERROR_LOG" # 遍历服务器列表 while IFS=' ' read -r ip username password port new_password; do echo "Processing server: ${ip}..." # 使用sshpass进行非交互式SSH登录 sshpass -p "${password}" ssh -o StrictHostKeyChecking=no -p "${port}" "${username}@${ip}" << EOF # 更新root密码 echo 'root:${new_password}' | chpasswd # 重启sshd以应用新密码 (可选,视需求而定) systemctl restart sshd EOF # 检查上一条命令是否成功 if [ $? -ne 0 ]; then echo "Error: Failed to update password for ${ip}. Check connectivity and credentials." >&2 echo "${ip} ${password}" >> "$ERROR_LOG" else echo "Password successfully updated for ${ip}." fi done < "${SERVER_LIST_FILE}" echo "Failed login details recorded in ${ERROR_LOG}"
serverlist.txt文件结构为:
ip 用户名 密码 端口 新密码
192.0.2.1 root oldpass1 22 newpass1
198.51.100.2 root oldpass2 22 newpass2
...
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.