DYI: Create Linux User by Hand


You know how to create Linux user account with useradd and passwd.But do you know, how to create it without using them? No, you can’t use adduser which is nothing but an symlink to ‘useradd

Why we need this? We believe Linux System-Admin should posses in-depth knowledge on things, rather than just depending on few binaries! So If you want to know what’s going on behind the scenes. Here we go:  Our task is to create user named  giis  and setup password. Lets first update the /etc/passwd  file with below entry 

echo "giis:x:25000:25000:Giis:/home/giis:/bin/bash" >> /etc/passwd

As you can see there are  7 fields separated by : where  each field refer to   

Field1:    giis - Login name   
Field2:    x    - Password place holder 
Field3:    25000  - Unique User id 
Field4:    25000  - Group id 
Field5:     giis  - Real name 
Field6:    /home/giis - Home directory 
Field7:    /bin/bash - Shell type

The summary of this entry would be – after verifying password for user giis in the /etc/shadow file, allow user  giis  to login  and place him under /home/giis with bash as the shell type. For a valid login, these fields must be sane. Above entry takes care of Field 1,3,5 and 7.  We need to restore sanity for Field 2, 4 and 6. 

We can setup Field-4 (group-id) by creating group-id under /etc/group file like 

echo "giis:x:25000" >> /etc/group

Above places an entry into group file which assigns, group name giis with Group-Id (aka gid ) 25000   Now we need to bring some sanity to field-6 (home-dir) by running a command : 

mkdir /home/giis

 which creates home directory and we set its permission appropriately with chown 

chown giis:giis /home/giis

As you can see below, new created home directory has rwx for own giis and non-writable to group/others.

 # ls -ld /home/giis drwxr-xr-x. 2 giis giis 4096 Sep 25 22:38 /home/giis

Finally we take care of field-2. It’s little complex than others.For any valid user password, it needs to be stored in encrypted format. Lets use below python statement to create a password secret897 and encrypted with sha256 algorithm using salt $6$salt1234  The end result will be encrypted string of secret897 with slat, which will be stored on /etc/shadow file. We stored encrypted password on temporary shell variable named pass 

pass=`python -c 'import crypt; print crypt.crypt("secret897", "$6$salt1234")'`

  change the permission of shadow file as writable by root 

    chmod 600 /etc/shadow

and just append the encrypted password along with username giis into the shadow file 

  echo "giis:${pass}:::::::" >> /etc/shadow

then revert the permission 

chmod 000 /etc/shadow

Now its time to log into the newly created account giis with password secret897 . Goto login prompt type your username and password, then it should place you under /home/giis with bash prompt like  bash-4.2$   Now verify your login identity using  whoami  and home directory using  pwd  
Everything Fine!  right?