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
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
--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:
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
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.
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.
You can run the passwd command and send it piped input. So, do something like:
echo thePassword | passwd theUsername --stdin