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

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

    For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:

    #!/bin/sh
    echo -n "Enter username: "
    read uname
    
    echo -n "Enter password: "
    read -s passwd
    
    adduser "$uname"
    echo $uname:$passwd | sudo chpasswd
    
    gpasswd wheel -a $uname
    
    0 讨论(0)
  • 2020-12-07 07:41

    --stdin doesn't work on Debian. It says:

    `passwd: unrecognized option '--stdin'`
    

    This worked for me:

    #useradd $USER
    #echo "$USER:$SENHA" | chpasswd
    

    Here we can find some other good ways:

    • http://www.debian-administration.org/articles/668
    0 讨论(0)
  • 2020-12-07 07:42

    The code below worked in Ubuntu 14.04. Try before you use it in other versions/linux variants.

    # quietly add a user without password
    adduser --quiet --disabled-password --shell /bin/bash --home /home/newuser --gecos "User" newuser
    
    # set password
    echo "newuser:newpassword" | chpasswd
    
    0 讨论(0)
  • 2020-12-07 07:44

    I liked Tralemonkey's approach of echo thePassword | passwd theUsername --stdin though it didn't quite work for me as written. This however worked for me.

    echo -e "$password\n$password\n" | sudo passwd $user
    

    -e is to recognize \n as new line.

    sudo is root access for Ubuntu.

    The double quotes are to recognize $ and expand the variables.

    The above command passes the password and a new line, two times, to passwd, which is what passwd requires.

    If not using variables, I think this probably works.

    echo -e 'password\npassword\n' | sudo passwd username
    

    Single quotes should suffice here.

    0 讨论(0)
  • 2020-12-07 07:44

    Tralemonkey's solution almost worked for me as well ... but not quite. I ended up doing it this way:

    echo -n '$#@password@#$' | passwd myusername --stdin
    

    2 key details his solution didn't include, the -n keeps echo from adding a \n to the password that is getting encrypted, and the single quotes protect the contents from being interpreted by the shell (bash) in my case.

    BTW I ran this command as root on a CentOS 5.6 system in case anyone is wondering.

    0 讨论(0)
  • 2020-12-07 07:45

    You can run the passwd command and send it piped input. So, do something like:

    echo thePassword | passwd theUsername --stdin
    
    0 讨论(0)
提交回复
热议问题