I had a couple of scripts working in the back end of an application to create users and set the passwords. So instead of reinventing the wheel I used the ?trusty? useradd.
Until recently one could pass the users password in clear text as a parameter. I assume that someone thought about all the passwords that word saved in history files and decided to change it. The problem is that the used the same parameter but now it expected the password to be encrypted, so it basically stopped working but didn’t generate errors.
After some debugging and some man reading the problem was nailed down, but now I had to generate and encrypt the password. I looked and tried many solutions but the best I could find was the crypt library and decided to access is through perl. What I liked the most about the solution is that I could use all the same native algorithms that the system has installed.
So lets cut the chase, here are the 5 lines of code needed to get the job done:
salt=$(/usr/bin/mkpasswd -l 8 -s 0)
encrypted=$(perl -e “$parameter”)
/usr/sbin/useradd -p $encrypted <user>
To create a good salt I used the mkpasswd utility that comes with the expect package (yum install expect). In this case the $1 is not a variable, but the way of telling crypt to use MD5.
Other valid values for the Glibc crypt are:
||Blowfish (not in mainline glibc; added in some Linux distributions)
||SHA-256 (since glibc 2.7)
||SHA-512 (since glibc 2.7)
For more information http://www.kernel.org/doc/man-pages/online/pages/man3/crypt.3.html or simply: man crypt