Skip to content
Go back

脚本中实现修改用户密码

Edit page

脚本中实现修改用户密码

平时在写脚本的时候, 有时候会需要使用passwd命令来修改用户的密码.
例如为NIS的测试服务器新增一些测试用户, 并且为这些用户设置密码.
由于passwd需要交互式的输入, 所以在脚本中使用passwd命令会报错.
一个潜在的解决方案是加入--stdin参数但是有的linux发行版中passwd命令中的--stdin不存在.
如果你还这样执行的话将会显示以下错误.

passwd: unrecognized option '--stdin'
Usage: passwd [options] [LOGIN]

Options:
  -a, --all                     report password status on all accounts
  -d, --delete                  delete the password for the named account
  -e, --expire                  force expire the password for the named account
  -h, --help                    display this help message and exit
  -k, --keep-tokens             change password only if expired
  -i, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -l, --lock                    lock the password of the named account
  -n, --mindays MIN_DAYS        set minimum number of days before password
                                change to MIN_DAYS
  -q, --quiet                   quiet mode
  -r, --repository REPOSITORY   change password in REPOSITORY repository
  -R, --root CHROOT_DIR         directory to chroot into
  -S, --status                  report password status on the named account
  -u, --unlock                  unlock the password of the named account
  -w, --warndays WARN_DAYS      set expiration warning days to WARN_DAYS
  -x, --maxdays MAX_DAYS        set maximum number of days before password
                                change to MAX_DAYS

由于passwd命令中没有--stdin选项, 所以我们需要使用其他的方式来解决这个问题.

解决方案

使用chpasswd

chpasswd命令可以用于批量修改用户的密码, 该命令的使用方法如下.

echo "user1:password1" | chpasswd

备注

不建议在脚本中修改密码, 因为这样会泄漏密码.
例如当脚本增加set -x选项时, 会将密码打印出来.
这种方式最好在测试环境中使用.

Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere. Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.

from

参考


Edit page
Share this post on:

Previous Post
升级springboot3遇到的问题
Next Post
基于clojure表达式实现更加灵活的数据验证