expect实现批量修改linux密码脚本分享
最近对linux批量执行的脚本很感兴趣,在网上到处找有关expect批量执行脚本,今天就给大家共享一个批量修改密码的脚本.
脚本内容:
#!/usr/bin/expect
if{$argc<2}{
send_user"usage:$argv0<hostfile><cmdfile>\n"
exit
}
#机器列表数据格式: IP 端口 旧密码 新密码
sethostfile [open[lindex$argv0]]
#命令列表数据格式: 一条命令一行
setcmdfile [open[lindex$argv1]]
#数据文件分割符,默认为空格
setpart"\"
#过滤关键字
setkey_password"password:\"
setkey_init"\(yes/no\)\?\"
setkey_confirm"'yes'\or\'no':\"
setkey_ps"*]#\"
setkey_newpassword"UNIXpassword:\"
settimeout30
log_file./exprct.log
match_max20480
while{[gets$hostfile_hosts_]>=0}{
sethosts[stringtrim$_hosts_]
setstr_index[stringfirst$part$hosts]
sethost[stringtrim[stringrange$hosts0$str_index]]
settemp[stringtrim[stringrange$hosts[expr$str_index+1][stringlength$hosts]]]
setstr_index[stringfirst$part$temp]
if{$str_index==-1}{
setport22
setpass$temp
setnewpass$temp
}else{
setport[stringtrim[stringrange$temp0$str_index]]
settemp_pass[stringtrim[stringrange$temp[expr$str_index+1][stringlength$temp]]]
setstr_index[stringfirst$part$temp_pass]
setpass[stringtrim[stringrange$temp_pass0$str_index]]
setnewpass[stringtrim[stringrange$temp_pass[expr$str_index+1][stringlength$temp_pass]]]
}
spawnssh-p$port$host
while{1}{
expect{
"$key_password"{
send"$pass\r"
}
"$key_init"{
send"yes\r"
}
"$key_confirm"{
send"yes\r"
}
"$key_ps"{
while{[gets$cmdfilecmd]>=0}{
send"$cmd\r"
expect{
"$key_ps"{
continue
}
"$key_newpassword"{
send"$newpass\r"
expect"$key_newpassword"{
send"$newpass\r"
expect"$key_ps"
continue
}
}
}
}
seek$cmdfile0start
send_user"\r"
break
}
timeout{
puts"$hosttimeout\n"
break
}
}
}
send"exit\r"
close
wait
}
close$hostfile
close$cmdfile
exit