本代码局限性比较大,需要保证.info.txt文件中的信息完全正确,否则会修改不成功,写的不是很好,有兴趣的可以研究下,大佬勿喷!!!
#!/bin/bash
# 查看当前目录下信息文件(info.txt)是否存在
if [ ! -f '.info.txt' ];then
echo -e "\033[31;40m .info.txt file does not exist \033[0m"
echo -e "file format: 远程主机 登录用户 登录密码 修改用户 修改密码\nexample : 192.168.1.1 root rootpass text testpass"
exit 0
fi
while read line
do
# 截取.info.txt的对应信息
host=$(echo $line|awk '{print $1}')
user=$(echo $line|awk '{print $2}')
pass=$(echo $line|awk '{print $3}')
port=$(echo $line|awk '{print $4}')
user2=$(echo $line|awk '{print $5}')
pass2=$(echo $line|awk '{print $6}')
# 执行expect命令,将结果输出到/root/alter_passwd.log
$(which expect) &>>/root/alter_passwd.log << EOF
# 设置超时5秒
set timeout 5
# 发送远程连接命令
spawn ssh -p$port $user@$host
# 第一次连接,接受到(yes/no),输入yes
expect {
"(yes/no)?" {
send "yes\r"
expect "*password"
send "$pass\r"
}
# 接受到password输入密码
"*password" {
send "$pass\r"
}
}
# 接受到#(为root用户)发送修改用户密码命令
expect {
"*#*" {
send "passwd $user2\r"
expect "*password:"
send "$pass2\r"
expect "*password:"
send "$pass2\r"
send "exit 1\r"
expect eof
}
# 接受到$(为普通用户)则切换到root用户发送修改用户密码命令
"*\$*" {
send "sudo su -\r"
expect "$user:"
send "$pass\r"
expect "#"
send "passwd $user2\r"
expect "*password:"
send "$pass2\r"
expect "*password:"
send "$pass2\r"
send "exit 1\r"
expect eof
}
}
EOF
done < .info.txt
echo "结果请查看/root/alter_passwd.log"