LINUX修改用户密码-交互式与非交互式
最近管理的一批机器,有个需求是要统一修改一个帐号的用户名密码,比如将qa帐号的密码改为1234,后来还为了脚本化,很方便的执行,还使用了非交互式地修改用户的密码。简单记录一下吧。
- 交互式配置本地用户的密码: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.
- 非交互式修改本地用户的密码: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.
- 使用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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
2019-12-24 python getattr函数的妙用
2019-12-24 python对mysql每个表备份
2019-12-24 shell script 在if 的判断条件正则表达式=~中引号问题
2018-12-24 k8s技术--Kubernetes集群kubectl命令的常见使用方法
2018-12-24 xargs与exec详解
2018-12-24 Nginx入门