Wednesday, July 15, 2009

Add Linux users with a crypted password

If you routinely setup Linux systems with the same user accounts, you might find it helpful to be able to add the users with a single command, without typing in the password and other info for each user like you have to do with adduser. A single-line, no-questions-ask command also lends itself well to batch scripting.

To do this you'll need to know the username, the system user id and group id (UID and GUID) and plain text password for the user you're about to add.

Start by making the crypted password hash. You can make the password hash with the following command (this is tested on Debian Linux):

    mkpasswd -H md5

mkpasswd will ask you for the password:

    Password:

Type in your password, hit enter and mkpasswd will show you the hash:

    $1$uv.y5wtb$remRyh2SeDD9mgZ81aYuB1

Here is the full command. Put the hash mkpasswd printed in single quotes at the end of the line like this:

    useradd -g 1003 -m -u 1003 -s /bin/bash johndoe -p '$1$uv.y5wtb$remByh2ShDD9mgZ81aYuB1'

The shell parameter "-s /bin/bash" is not strictly necessary but I've found it best to include it to avoid potential accidents.

Note that when using useradd like this, the groups must be preexisting. If the group doesn't already exist, add it with:

    groupadd groupname

It's a good idea to clear your shell history after adding all your users this way. An easy way to clear the history is by running the following commands, one at a time:

    HISTFILESIZE=1
    ls
    ^d

(^d means Ctrl-d: hold down the control key, tap the d key, then let go of the controll key)

No comments: