Junk Food for the Brain

Open Source and Awesomesauce :)

How to Change Passwords in Linux Using a Shell Script

| Comments

There are times when you would need to change the local user password for a whole bunch of Linux machines at one go. If they weren’t using the a directory service like NIS or LDAP, you’d be in for a lot of pain.

Fortunately, the passwd command comes with a handy option that allows this relatively insecure method.

Let’s assume you want to change the password for a system account called webapp450 on 5 servers, named web001, web002, web003, database001 and database002. The passwd command contains a switch that allows root to receive the password via stdin.

# passwd --stdin

What you could do is use the echo command to pipe the new password in. E.g.

# echo 'newpassword' | passwd --stdin webapp450

Now, we can add this into a script:

# chgpasswd.sh
export HISTIGNORE="*passwd*"
echo 'newpassword' | passwd --stdin webapp450

I created a bash script called chgpasswd.sh and changed its permissions to 700, so only root could read & execute it. For a little added security, I even added the bash HISTIGNORE command, that ignores any line containing the word passwd, so it doesn’t get added to the bash history file.

I then dumped it in a directory that was shared among those 5 hosts (/shared) and ran it via ssh.

As a final bit of automation, I ran in using the following bash for loop:

$ for machine in web001 web002 web003 database001 database002; do ssh root@$machine '/shared/chgpasswd.sh'; done

Note: This method is highly insecure, and should be only used if you know what you’re doing.