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

前端 未结 19 713
北荒
北荒 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:27

    I was asking myself the same thing, and didn't want to rely on a Python script.

    This is the line to add a user with a defined password in one bash line:

    useradd -p $(openssl passwd -crypt $PASS) $USER
    
    0 讨论(0)
  • 2020-12-07 07:27

    Single liner to create a sudo user with home directory and password.

    useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}
    
    0 讨论(0)
  • 2020-12-07 07:28

    I know I'm coming at this years later, but I can't believe no one suggested usermod.

    usermod --password `perl -e "print crypt('password','sa');"` root
    

    Hell, just in case someone wants to do this on an older HPUX you can use usermod.sam.

    /usr/sam/lbin/usermod.sam -F -p `perl -e "print crypt('password','sa');"` username
    

    The -F is only needed if the person executing the script is the current user. Of course you don't need to use Perl to create the hash. You could use openssl or many other commands in its place.

    0 讨论(0)
  • 2020-12-07 07:31
    { echo $password; echo $password; } | passwd $username 
    
    0 讨论(0)
  • 2020-12-07 07:34

    I've tested in my own shell script.

    • $new_username means newly created user
    • $new_password means newly password

    For CentOS

    echo "$new_password" | passwd --stdin "$new_username"
    

    For Debian/Ubuntu

    echo "$new_username:$new_password" | chpasswd
    

    For OpenSUSE

    echo -e "$new_password\n$new_password" | passwd "$new_username"
    
    0 讨论(0)
  • 2020-12-07 07:34

    The solution that works on both Debian and Red Hat. Depends on perl, uses sha-512 hashes:

    cat userpassadd
        #!/usr/bin/env bash
    
        salt=$(cat /dev/urandom | tr -dc A-Za-z0-9/_- | head -c16)
        useradd -p $(perl -e "print crypt('$2', '\$6\$' . '$salt' . '\$')") $1
    

    Usage:

    userpassadd jim jimslongpassword
    

    It can effectively be used as a one-liner, but you'll have to specify the password, salt and username at the right places yourself:

    useradd -p $(perl -e "print crypt('pass', '\$6\$salt\$')") username
    
    0 讨论(0)
提交回复
热议问题