Problem
I want to use a shell script to automate account creation and password assignment on my UnixWare 7 system. How can I make the script handle the interactive passwd command?
Solution
Create a file where each line has the login name and password for an account; this file can be used as input for the following account creation script. The contents of such a file might look similar to this:
sally abc99043
billy qrs82345
john lmn45678
kimmy jgt56995
.
.
.For our example, let's say this file is called /tmp/users. Script number 1 (below) will read the file /tmp/users one line at a time and create a home directory for the user, add the user, then call script number 2 (mkpass) to set the account password without interactive input. Both scripts should reside in the same directory, have permissions of 755, and be run as root. In script 1, /home is the filesystem where user's home directories will reside. Be sure to change this to the filesystem appropriate for your system. Also, the options chosen for the 'useradd' command were chosen for example purposes only. Check the useradd man page for the options appropriate to your needs.
------------------------- script number 1 ----------------------#!/bin/ksh
# script name = mkaccts
# reads login name and matching password from /tmp/users
# creates a home directory in /home filesystem, adds the
# user, then calls mkpass to set the password cat /tmp/users | \
while read LOGIN PASSWD
do
useradd -m -d /home/$LOGIN -s /bin/ksh $LOGIN
./mkpass $LOGIN $PASSWD
done
----------------------------------------------------------------------------------------- script number 2 (mkpass) -------------#!/usr/bin/expect -f
# script name = mkpass
# wrapper to make passwd(1) be non-interactive
# username is passed as 1st arg, passwd as 2nd set password [lindex $argv 1]
spawn passwd [lindex $argv 0]
expect "password:"
send "$password\r"
expect "password:"
send "$password\r"
expect eof
----------------------------------------------------------------NOTE: When run, this script will display each password as it is set. To
bypass this potential security breach, redirect output to:/dev/nullNOTE: To quickly add x and/or delete x users try:--------------------------- addthem ----------------------------
count=1
while true
do
echo $count
count=`expr ${count} + 1`
if [ $count = 1001 ]; then
exit
fi
useradd -m user$count
done
-------------------------------------------------------------------------------------------- rmthem ----------------------------
count=1
while true
do
echo $count
count=`expr ${count} + 1`
if [ $count = 1001 ]; then
exit
fi
userdel -r -n 0 user$count
done
----------------------------------------------------------------