Linux Shell script to add a user with a password to the system
Linux Tips September 20th, 2007A. 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:
#!/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.
——————- another hint —-
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 \"$rpaswdn\"; 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”);
————————–
To display user list just type:
cut -d: -f1 /etc/passwd
gawk -F: ‘{ if ( $3>500 ) print $1 }’/etc/passwd
Recent Comments