一、自动化执行批量修改密码,需要配置一个主机列表,包含[ hostname ip username password ],读取列表文件,逐台进行修改,需要expect进行自动化登陆,运行的脚本程序为:
#!/bin/bash
#--------------------------------------------------------------------------------------------------------
# parallel send and execute command to destination
# The command format
# sh pssh.sh -p new_password
# 参数说明:
# -p 指定需要统一修改的新密码,expect
#--------------------------------------------------------------------------------------------------------
basepath=$(cd `dirname $0`; pwd)
ip_list_path=$basepath/host.info
#verify whether the parameters is right
verifyparameters () {
while [ -n "$1" ]
do
case $1 in
-p) new_password="$2"
echo "found the -p option, with parameter value $new_password"
shift 1;;
-?) echo "Unkown option $1, all options are [-p] and others is invalid!";;
esac
shift
done
}
verifyparameters "$@"
if [[ -z $new_password ]];then
echo "[ERROR] new_password is null, use -p to set!"; exit
fi
echo "`date +'%Y-%m-%d %H:%M:%S'` [INFO] start change user password..."
#将逐个修改各个节点的密码
while read node
do
hostname=$(echo $node | awk '{print $1}')
ip=$(echo $node | awk '{print $2}')
username=$(echo $node | awk '{print $3}')
password=`echo $node | awk '{print $4}'`
if [[ -n $ip ]];then
$basepath/expect_change $username $ip $password $new_password
echo "`date +'%Y-%m-%d %H:%M:%S'` [INFO] change $ip $username password success!"
sleep 1
fi
done <$ip_list_path
echo "`date +'%Y-%m-%d %H:%M:%S'` [INFO] change finished."
脚本需要调用expect_change执行自动化修改,expect_change的程序为:
#!/usr/bin/expect
#--------------------------------------------------------------------------------------------------------
# 该文件主要是进行密码修改
# 命令格式
# check.expect $username $ip $password $file_md5 $command $local_file_path $remote_file_path
# 参数说明:
# username 远程主机的用户名
# ip 远程主机的IP
# password 远程主机的密码
# new_password 需要修改的新密码
#--------------------------------------------------------------------------------------------------------
#初始化变量
set username [lindex $argv 0]
set ip [lindex $argv 1]
set password [lindex $argv 2]
set new_password [lindex $argv 3]
set timeout 1
#登录远程主机,当密码中出现-字符时,发送密码,expect会将后面的字符串转为方法,需要加--解决
spawn ssh ${username}@${ip}
expect {
"*yes/no*" {send "yes\r"; exp_continue}
"*assword*" {send -- "$password\r"; exp_continue}
}
#修改密码,如果是普通用户,有可能需要先验证Old Password,如果需要加上即可
send "passwd\r";
expect {
"*New Password:" {send -- "$new_password\r"; exp_continue}
"*Reenter New Password:" {send -- "$new_password\r";}
}
expect eof;
exit;
二、遇到的问题
登录远程主机,当密码中出现-字符时,发送密码会报错,错误如下:
: must be -i, -h, -s, -null, -0, -raw, -break, or —
while executing
expect会将后面的字符串转为方法,需要加--解决,因为--标志强制下一个参数被解释为一个字符串而不是一个标志.所以,尽可能在可能会出现特殊字符的变量前面都加上--。