Linux下交互式与非交互式修改用户密码的例子
最近管理的一批机器,有个需求是要统一修改一个帐号的用户名密码,比如将qa帐号的密码改为1234,后来还为了脚本化,很方便的执行,还使用了非交互式地修改用户的密码。简单记录一下吧。
1.交互式配置本地用户的密码:passwd命令
[root@host_221-81~]#passwdqa Changingpasswordforuserqa. Newpassword: BADPASSWORD:itistooshort BADPASSWORD:istoosimple Retypenewpassword: passwd:allauthenticationtokensupdatedsuccessfully.
2.非交互式修改本地用户的密码:chpasswd
#chpasswd命令使用起来很简洁 [root@host_221-81~]#echo"qa:1234"|chpasswd #使用passwd命令,也可以实现非交互式修改密码 [root@host_221-81~]#echo"1234"|passwd--stdin"qa" Changingpasswordforuserqa. passwd:allauthenticationtokensupdatedsuccessfully.
3.使用expect来处理交互式输入,从而实现非交互式的密码修改。
#!/bin/sh #\ execexpect-f"$0""$@" if{$argc!=2}{ puts"Usage:$argv0<username><passwd>" exit1 } setpassword[lindex$argv1] spawnpasswd[lindex$argv0] sleep1 expect"assword:" send"$password\r" expect"assword:" send"$password\r" expecteof
注意:脚本的第二行,这种写法可能比较陌生,这是在TCL语言中的语法,Thebackslashisrecognizedaspartofacommenttosh,butinTclthebackslashcontinuesthecommentintothenextlinewhichkeepstheexeccommandfromexecutingagain.
该脚本的执行结果为:
[root@smilejay~]#./change-pwd-expect.shqa1234 spawnpasswdqa Changingpasswordforuserqa. Newpassword: BADPASSWORD:itistooshort BADPASSWORD:istoosimple Retypenewpassword: passwd:allauthenticationtokensupdatedsuccessfully.