Skip to content

13 密码检查更新与批量创建账号

1. 账号检查工具

1.1 pwck

pwck [options] [passwd [ shadow ]]
验证密码文件的完整性

options
    -q, --quiet                   report errors only
    -r, --read-only               display errors and warnings,不修改文件
[root@dev ~]# pwck /etc/passwd
# 没有家目录
user 'saslauth': directory '/run/saslauthd' does not exist
user 'pulse': directory '/var/run/pulse' does not exist
user 'gnome-initial-setup': directory '/run/gnome-initial-setup/' does not exist
pwck: no changes

群组的检查指令是grpck

1.2 pwconv

pwconv, pwunconv, grpconv, grpunconv
conv:将密码从passwd转换到shadow中,unconv:反向操作,并且删除shadow文件!!!

1.3 chpasswd

chpasswd [options]
批量更新(不能新建不存在的用户和密码)密码,从标准输入读取用户名和密码对的列表,并使用此信息更新一组现有用户(从 /etc/login.def 读取加密机制)

Options:
    -c, --crypt-method METHOD     the crypt method (one of NONE DES MD5 SHA256 SHA512)
    -e, --encrypted               supplied passwords are encrypted
    -m, --md5                     encrypt the clear text password using the MD5 algorithm
[root@dev ~]# grep user /etc/shadow
user1:$6$3KY4ypLh$jpUYfSIhNBmDzsuH/ehSxLYkfd.e88c1WQpBBTeHMJUhjuh0KUfEJGkOEcyp0/lBOSI2h3/n8iiPZ0ZOxfM.l.:18183:0:99999:7:::
user2:!!:18183:0:99999:7:::
[root@dev ~]# chpasswd <<!
> user1:156 user2:654321
> !
# 可见原本有密码的用户更新了,但是禁用密码的用户没有更新
[root@dev ~]# grep user /etc/shadow
user1:$6$2zO4d8.N0Cfh$xfwK3RfVyFhmm3JxXcrOCTtEdKlzmAGz1C5OuUq/tKNmkavfHHUIuNjXvlv0QIgetwk6Qb2F8qn4IjxT1JmKg0:18186:0:99999:7:::
user2:!!:18183:0:99999:7:::

[root@dev ~]# echo "user4:5475676" | chpasswd
chpasswd: line 1: user 'user4' does not exist
chpasswd: error detected, changes ignored

2. 创建大量账号

可以使用 newusers 或下面的脚本:

[sink@dev study]$ cat create-accounts.sh
#!/bin/sh

export PATH=/usr/local/bin:/usr/local/sbin:/usr/bin/:/usr/sbin/

action=$1
usergrp=$2

action=${action:-create}

if [ "$action" != "create" -a "$action" != "delete" ]; then
        echo "action is not correct."
        exit 1
fi

if [ ! -f accounts ];then
        echo "there is no accounts to read."
        exit 1
fi

[ "$usergrp" != "" ] && usergrp="-G ${usergrp}" || usergrp=""

rm -f passwds

case $action in
        "create")
                for a in $(cat accounts)
                do
                        tmp_passwd=$(openssl rand -base64 1) && useradd $usergrp $a && echo ${tmp_passwd} | passwd --stdin $a
                        chage -d 0 $a
                        echo "$a ${tmp_passwd}" >> passwds
                done
                ;;
        "delete")
                for a in $(cat accounts)
                do
                        userdel -r $a
                done
esac