Sunday, November 25, 2012

Linux Shell script to add a user with a password to the system

Our regular reader Imtiaz asks:
How do I add a user with password? I’d like to take input such as username, password from keyboard and add to the system under Linux.
A. You can easily write a shell script that reads username, password from keyboard and add to /etc/passwd and /etc/shadow file using useradd command (create a new user command).
General syntax is as follows:
useradd -m -p encryptedPassword username
Where,
  • -m : The user’s home directory will be created if it does not exist.
  • useradd -p encryptedPassword : The encrypted password, as returned by crypt().
  • username : Add this user to system

Task: Create an encrypted password

You need to create encrypted password using perl crypt():
$ perl -e 'print crypt("password", "salt"),"\n"'
Output:
sa3tHJ3/KuYvI 
Above will display the crypted password (sa3tHJ3/KuYvI) on screen. The Perl crypt() function is a one way encryption method meaning, once a password has been encrypted, it cannot be decrypted. The password string is taken from the user and encrypted with the salt and displayed back on screen.
You can store an encrypted password using following syntax:
$ password="1YelloDog@"
$ pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
$ echo $pass

Output
paU5t8Al/qf6M

Sample shell script to add a user

Based upon above discussion here is a sample shell script (Download link):
#!/bin/bash
# Script to add a user to Linux system
if [ $(id -u) -eq 0 ]; then
 read -p "Enter username : " username
 read -s -p "Enter password : " password
 egrep "^$username" /etc/passwd >/dev/null
 if [ $? -eq 0 ]; then
  echo "$username exists!"
  exit 1
 else
  pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
  useradd -m -p $pass $username
  [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
 fi
else
 echo "Only root may add a user to the system"
 exit 2
fi
Close and save the script:
$ ./adduser.sh
Only root may add a user to the system
Run as root:
# ./adduser
Output:
Enter username : roja
Enter password : HIDDEN
User has been added to system!
Now user roja can login with a password called HIDDEN.