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 ]#
Tralemonkey's solution almost worked for me as well ... but not quite. I ended up doing it this way:
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.
I've tested in my own shell script.
$new_username
means newly created user$new_password
means newly passwordFor CentOS
For Debian/Ubuntu
For OpenSUSE
The solution that works on both Debian and Red Hat. Depends on perl, uses sha-512 hashes:
Usage:
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:
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.-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 whatpasswd
requires.If not using variables, I think this probably works.
Single quotes should suffice here.
For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:
The following works for me and tested on Ubuntu 14.04. It is a one liner that does not require any user input.
Taken from @Tralemonkey