How to automatically add user account AND password

2020-02-07 13:50发布

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 easy to create the user via Bash e.g.:

[whoever@server ]#  /usr/sbin/useradd newuser

Is it possible to assign a password in Bash, something functionally similar to this, but automatically:

[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password: 
passwd: all authentication tokens updated successfully.
[whoever@server ]#

19条回答
相关推荐>>
2楼-- · 2020-02-07 14:29

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

echo thePassword | passwd theUsername --stdin
查看更多
在下西门庆
3楼-- · 2020-02-07 14:29

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.

查看更多
beautiful°
4楼-- · 2020-02-07 14:31

usage: ./my_add_user.sh USER PASSWD

code:

#!/bin/bash
# my_add_user.sh

if [ "$#" -lt 2 ] 
 then
       echo "$0 username passwd"
       exit
fi

user=$1
passwd=$2

useradd $user -d /data/home/$user  -m  ;
echo $passwd | passwd $user --stdin;
查看更多
小情绪 Triste *
5楼-- · 2020-02-07 14:31

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 -1 $PASS) $USER
查看更多
男人必须洒脱
6楼-- · 2020-02-07 14:31

--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:

查看更多
▲ chillily
7楼-- · 2020-02-07 14:33

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
查看更多
登录 后发表回答