IT技术博客大学习 共学习 共进步

Linux修改用户密码-交互式与非交互式

笑遍世界 2015-01-27 22:36:36 浏览 2,742 次

最近管理的一批机器,有个需求是要统一修改一个帐号的用户名密码,比如将qa帐号的密码改为1234,后来还为了脚本化,很方便的执行,还使用了非交互式地修改用户的密码。简单记录一下吧。

1. 交互式配置本地用户的密码:passwd 命令

1
2
3
4
5
6
7
[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

1
2
3
4
5
6
7
# 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来处理交互式输入,从而实现非交互式的密码修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/sh# \exec expect -f"$0""$@"if{$argc!= 2}{puts "Usage: $argv0 <username> <passwd>"exit1}set password [lindex $argv1]
spawn passwd[lindex $argv0]sleep1
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.

该脚本的执行结果为:

1
2
3
4
5
6
7
8
[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.

参考资料:http://wiki.tcl.tk/708#pagetoc593413fa

建议继续学习

  1. 网站密码存储方案比较 (阅读 6,542)
  2. 解决linux下安装ssl后,apache重启时需要密码 (阅读 6,383)
  3. 懒人连ssh不输密码若干大法 (阅读 5,483)
  4. SSH无密码登录 (阅读 5,482)
  5. 利用QQ游戏破解QQ密码 (阅读 5,182)
  6. Linux各版本root密码的本地破解方法 (阅读 4,922)
  7. CSDN明文口令泄露的启示 (阅读 4,662)
  8. 懒人连ssh不输密码若干大法 (阅读 4,225)
  9. 正确重置MySQL密码 (阅读 4,222)
  10. 为什么一定要有密码? (阅读 3,962)