Changing Solaris password with an expect script

Changing a users password without user keyboard input is very easy under Linux by using the builtin command "chpasswd "or "passwd --stdin". Solaris doesn't have such commands, the result can be achieved by expect script.

#Expect script

$ cat chpwd.sh

#!/usr/local/bin/expect --
# Input: username password
set USER [lindex $argv 0]
set PASS [lindex $argv 1]

if { $USER == "" || $PASS == "" }  {
   puts "Usage:  ./scriptname username password\n"
   exit 1
 }
spawn sudo passwd $USER 
expect "assword:"
send "$PASS\r"
expect "assword:"
send "$PASS\r"
expect eof

#Shell script: Generate a random password and call the Expect script to set it

$ cat createpwd.sh

#!/bin/ksh
# Generate a random password  for a user and set the new password 
USER=$1
PASS=`tr -dc [:alnum:] </dev/urandom | fold -8 | head -1`
if [ -z "$USER" ]; then
echo "Usage $0 username"
exit
fi
./chpwd.sh $USER $PASS
echo "username=$USER"
  
echo "password=$PASS"