Linux Update Password Script

In my last post I showed a good example for using expect in a script.  Here is another good example I use for updating local user passwords across a group of servers without using ssh keys.  This assumes the user you are resetting can ssh to the host and the old password is the same on all hosts.

#!/bin/sh
# $Id: password_change.sh 6 2009-03-09 18:57:02Z jaredo $
#
# Copyright (c) 2009 Jared Orzechowski <jaredo at ameritech dot net>
#
# Description:  This script will ssh to servers and change the specified
# users password (assuming user can ssh).  Requires expect package.
 
USER=""
OLDPW=""
NEWPW=""
 
function resetpw()
{
        if [ "$1" ]; then
          echo
          echo "Attempting to reset password for $USER on host $1.."
 
              CMD="ssh -l root $1 passwd $USER"
              expect -c "
              match_max 100000
              spawn $CMD
 
              expect {
                \"Are you sure you want to continue connecting (yes/no)?\" {
                send \"yes\r\"
                exp_continue
                }
                \"s password:\" {
                send \"$OLDPW\r\"
                exp_continue
                }
                \"UNIX password:\" {
                send \"$NEWPW\r\"
                exp_continue
                expect -re \"$USER*\"
                }
              }
              "
        else
          echo "Missing hostname.."
        fi
}
 
#Syntax: resetpw hostname
#Example:
resetpw myserver1
resetpw myserver2
resetpw myserver3
resetpw myserver4

Leave a Reply

Your email address will not be published. Required fields are marked *