这篇文章主要介绍“如何实现Linux下交互式与非交互式修改用户密码”,在日常操作中,相信很多人在如何实现Linux下交互式与非交互式修改用户密码问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何实现Linux下交互式与非交互式修改用户密码”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
1. 交互式配置本地用户的密码:passwd 命令
代码如下:
[root@host_221-81 ~]# passwd qa
Changing password for user qa.
New password:
BAD PASSWORD: it is too short
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.
2. 非交互式修改本地用户的密码:chpasswd
代码如下:
# chpasswd命令使用起来很简洁
[root@host_221-81 ~]# echo "qa:1234" | chpasswd
# 使用passwd命令,也可以实现非交互式修改密码
[root@host_221-81 ~]# echo "1234" | passwd --stdin "qa"
Changing password for user qa.
passwd: all authentication tokens updated successfully.
3. 使用expect来处理交互式输入,从而实现非交互式的密码修改。
代码如下:
#!/bin/sh
# \
exec expect -f "$0" "$@"
if { $argc != 2 } {
puts "Usage: $argv0 <username> <passwd>"
exit 1
}
set password [lindex $argv 1]
spawn passwd [lindex $argv 0]
sleep 1
expect "assword:"
send "$password\r"
expect "assword:"
send "$password\r"
expect eof
注意:脚本的第二行,这种写法可能比较陌生,这是在TCL语言中的语法,The backslash is recognized as part of a comment to sh, but in Tcl the backslash continues the comment into the next line which keeps the exec command from executing again.
该脚本的执行结果为:
代码如下:
[root@smilejay ~]# ./change-pwd-expect.sh qa 1234
spawn passwd qa
Changing password for user qa.
New password:
BAD PASSWORD: it is too short
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.
到此,关于“如何实现Linux下交互式与非交互式修改用户密码”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注天达云网站,小编会继续努力为大家带来更多实用的文章!