How to automatically add user account AND password with a Bash script?

前端 未结 19 758
北荒
北荒 2020-12-07 06:53

I need to have the ability to create user accounts on my Linux (Fedora 10) and automatically assign a password via a bash script(or otherwise, if need be).

It\'s eas

19条回答
  •  我在风中等你
    2020-12-07 07:25

    Here is a script that will do it for you .....

    You can add a list of users (or just one user) if you want, all in one go and each will have a different password. As a bonus you are presented at the end of the script with a list of each users password. .... If you want you can add some user maintenance options

    like:

    chage -m 18 $user
    chage -M 28 $user
    

    to the script that will set the password age and so on.

    =======

    #!/bin/bash
    
    # Checks if you have the right privileges
    if [ "$USER" = "root" ]
    then
    
    # CHANGE THIS PARAMETERS FOR A PARTICULAR USE
    PERS_HOME="/home/"
    PERS_SH="/bin/bash"
    
       # Checks if there is an argument
       [ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
       # checks if there a regular file
       [ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
       TMPIN=$(mktemp)
       # Remove blank lines and delete duplicates 
       sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"
    
       NOW=$(date +"%Y-%m-%d-%X")
       LOGFILE="AMU-log-$NOW.log"
    
       for user in $(more "$TMPIN"); do
          # Checks if the user already exists.
          cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
          OUT=$?
          if [ $OUT -eq 0 ];then
             echo >&2 "ERROR: User account: \"$user\" already exists."
             echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
          else
             # Create a new user
             /usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
             # passwdgen must be installed
             pass=$(passwdgen -paq --length 8)
             echo $pass | passwd --stdin $user
             # save user and password in a file
             echo -e $user"\t"$pass >> "$LOGFILE"
             echo "The user \"$user\" has been created and has the password: $pass"
          fi
       done
       rm -f "$TMPIN"
       exit 0
    else
       echo >&2 "ERROR: You must be a root user to execute this script."
       exit 1
    fi
    

    ===========

    Hope this helps.

    Cheers, Carel

提交回复
热议问题