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

by Vivek Gite · 30 comments

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.

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 30 comments… read them below or add one }

1 Amol P Kesare 03.22.07 at 5:22 am

I just want to send one script which I have made for changing password of any user from remote machine.
Here I have created one file called “host” which contents host ips.

Shell script code

#!/bin/bash
read -p "Enter Username: " username
read -ers -p "Enter New password for user $username: " paswd
echo
read -ers -p "Enter Root Password: " rpaswd
echo
password=`python file ${paswd}`;
echo "$username $password $npaswd"
cat host | while read line
do
#####expect####
status=$(expect -c "
spawn ssh $line usermod -p $password $username
expect {
password: { send \"$rpaswd\n\"; exp_continue }
}
exit
")

echo ""
echo "$status" > log.txt
#####end of expect#######
done

python code – file [for crypt()]

import crypt; import sys; print crypt.crypt(sys.argv[1],”salt”);

Hope this will help somebody. :)
Cheers!

2 nixcraft 03.22.07 at 8:27 am

Amol,

Nice script.

Appreciate your post.

3 Amol P Kesare 03.22.07 at 9:52 am

Hey forgot one thing….there is one more file called “file”, and contents of these files are -

import crypt; import sys; print crypt.crypt(sys.argv[1],”salt”);

4 nixcraft 03.22.07 at 9:59 am

Yes, i thought so… there is line about python… thanks

5 Allotment 03.23.07 at 1:00 pm

I always wondered if there was a bash /CLI command to list the users, is there?
I see here
egrep “^$username” /etc/passwd >/dev/null

so there is not?

6 nixcraft 03.23.07 at 2:25 pm

Remove ‘>/dev/null‘ and you should see username if exists in /etc/passwd. To display list just type:

cut -d: -f1 /etc/passwd

7 master 03.26.07 at 7:22 am

its great but it is more powerful if you include the functionality to add lage number of users at once
like in my uni more then 15000 stuent it is almoste inpossible to create their acccounts one by one

8 nixcraft 03.26.07 at 6:54 pm

master,

You may take help of this my previous post – How to create multiple users accounts in batch / bulk

HTH

9 balakrishnan.R 04.13.07 at 11:24 am

How I need edit the script to add the user in particular group and disable them by accessing telnet.

example:

useradd -d /home/example1 -s /bin/false -g popusers example1

10 Amol P Kesare 04.17.07 at 6:03 am

># Allotment Says:
>March 23rd, 2007 (4 weeks ago) at 1:00 pm
>I always wondered if there was a bash /CLI command >to list the users, is there?
>I see here
>egrep “^$username” /etc/passwd >/dev/null
>so there is not?

You can use gawk to list users
gawk -F: ‘{ if ( $3>500 ) print $1 }’/etc/passwd

11 Fabio 05.09.07 at 5:03 pm

Could you kindly help me to integrate in this first script to add a user in /etc/shadow from a comma separeted file?
I would like to export a list from a company application, create a .csv , and lunch it from a shell script or a php page in a website to import users in 1 step.
The important is that the password used to access sistem by users is the one I can read in clear characters in the csv file.
Let me know please, and put my address in copy fabio@conecta.it

12 bhushan 08.10.07 at 6:56 am

egrep “^$username” /etc/passwd

don’t u people think that this will not match string
perfectly means if there is user like bhushan and i want to create user bhush…then it will give msg that user already exists…

13 vivek 08.10.07 at 7:18 am

Sure you can use word based matching:

egrep -w “^$username” /etc/passwd
14 Slavko 08.10.07 at 8:02 am

(echo "username:password")|chpasswd

15 bhushan 08.14.07 at 10:43 am

hi vivek,
how to add user without using useradd command?
With all information such as uid(by incrementing existing highest one), gid,…….etc.

16 Tyler McAdams 08.18.07 at 4:20 pm

I need a shell script that will create a password for users already on the system. How can I do that?

17 Artem Nosulchik 09.19.07 at 2:45 pm

Another way to get encrypted password is command:

openssl passwd yourpass

18 Eric Daza 06.06.08 at 4:09 am

PASSWORD checking is limited to 8 characters long.

I tried the Script above (adduser.sh), and the password checking is some how up-to 8 characters only. Meaning as long as you have the first 8 characters correct you can login to the system (I tested using su command)
The part I changed on the script is to set username and password as a variable:

username=test
password=secr3t12345

ex.
password=secr3t12345

it will allow secr3t12333333333 or secr3t12

19 Lakh 12.18.08 at 7:14 pm

How can you also get this script to add a samba password at the same time it creates a unix password?

20 Lonnie Waugh 02.02.09 at 5:55 pm

Useful article, I was was looking to add users with a one liner so this helped .. since Debian lacks the crypt command, I didn’t even think to use perl ..

Since I maintain the web server we use, exclusively .. I know all of my accounts have home directories, so I simply do my test to see if a user exists in perl .. but the same could be done in a shell script

if (-e “/home/$username”) {
print “The account already exists bonehead!”;
exit;
} else {
// get on with it
}

21 laknath 02.21.09 at 7:41 pm

hi,
i compile this program but when i move to the second part I cant execute it in root . I got a error???

No such file or directory

why is that ???
pls reply me….

22 rapsa 03.16.09 at 2:32 pm

how about this one liner script

# useradd -m -p `perl -e ‘print crypt(“your_password”, “salt”),”\n”‘` your_username

23 palani 03.25.09 at 7:23 am

hi
how to create new user to assign perssion to particular shell and set userid and groupid make this one line command

24 Mukundan 05.28.09 at 3:01 pm

HI

I like to add bulk of user using bash scripting taking the user name from a text file from a given location and also want to set a sample passwd for the all user who have been created. and also the script has to mail to the corresponding user regarding the username and passwd . Can anyone help me out

Thanks in advance

25 Gordon 06.02.09 at 10:29 pm

Sample shell script to add a user

How do I change this to add the users full name ans login shell

26 Charanjit Singh 07.05.09 at 8:59 am

Hi Vivek(nixcraft)
Your mentioned shell script giving me an error message while executing it
“line 19: syntex error: unexpected end of the file”
Please check and where it is get stuck..
Thanks
Charanjit Singh

27 Dnyan 08.17.09 at 4:50 pm

Hi all,

Can someone let me know, How to write script for password expiry notification in solaries.

28 Ravi Sajjan 10.23.09 at 8:25 am

Hello Everyone,
My self Ravi and I am trying to make one PHP page, from which i can able to create
new user in linux. where in php code will show three boxes
1.) New User Name:
2.) Password:
3.) Botton: Add now
with this php code i want to add new user in linux through web interface.

Kindly please help me out to do that so.

Regadrs,
Ravi

29 Harold Osborn 01.15.10 at 4:30 am

i need to help me. i want to good 100% user email, password and forget password.
frisrt sign user email then get get password number in then open in base.
if forget password then send email get password
Can anyone help me thank harold

30 majo053 02.06.10 at 11:23 pm

simple: echo PASSWORD | passwd USER –stdin

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post: