网硕互联技术交流社区

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 2520|回复: 0

Linux下交互式与非交互式修改用户密码的例子

[复制链接]

4

主题

4

帖子

42

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
42
发表于 2017-5-8 09:41:09 | 显示全部楼层 |阅读模式
最近管理的一批机器,有个需求是要统一修改一个帐号的用户名密码,比如将qa帐号的密码改为1234,后来还为了脚本化,很方便的执行,还使用了非交互式地修改用户的密码。简单记录一下吧。
1. 交互式配置本地用户的密码:passwd 命令

  1. [root@host_221-81 ~]# passwd qa
  2. Changing password for user qa.
  3. New password:
  4. BAD PASSWORD: it is too short
  5. BAD PASSWORD: is too simple
  6. Retype new password:
  7. passwd: all authentication tokens updated successfully.
复制代码


2. 非交互式修改本地用户的密码:chpasswd


  1. # chpasswd命令使用起来很简洁
  2. [root@host_221-81 ~]# echo "qa:1234" | chpasswd

  3. # 使用passwd命令,也可以实现非交互式修改密码
  4. [root@host_221-81 ~]# echo "1234" | passwd --stdin "qa"
  5. Changing password for user qa.
  6. passwd: all authentication tokens updated successfully.
复制代码


3. 使用expect来处理交互式输入,从而实现非交互式的密码修改。
  1. #!/bin/sh
  2. # \
  3. exec expect -f "$0" "$@"
  4. if { $argc != 2 } {
  5.     puts "Usage: $argv0 <username> <passwd>"
  6.     exit 1
  7. }
  8. set password [lindex $argv 1]
  9. spawn passwd [lindex $argv 0]
  10. sleep 1
  11. expect "assword:"
  12. send "$password\r"
  13. expect "assword:"
  14. send "$password\r"
  15. 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. [root@smilejay ~]# ./change-pwd-expect.sh qa 1234
  2. spawn passwd qa
  3. Changing password for user qa.
  4. New password:
  5. BAD PASSWORD: it is too short
  6. BAD PASSWORD: is too simple
  7. Retype new password:
  8. passwd: all authentication tokens updated successfully.
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|网硕互联技术交流社区

GMT+8, 2024-5-1 08:01 , Processed in 0.220190 second(s), 21 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表