0

I want to change root password of multiple server's. I used shell with for loop and chpasswd utility to do this. Since the sudo account is password enabled, it is prompting sudo password all the time I exit script.

Below is bash Script is written in bash. But always prompting for password.

#!/bin/bash
pass="PASSWORD"

for i in $(cat serverlist)

do

ssh -t sudouser@$i "sudo chpasswd <<EOF

root:"$pass"

EOF" ;

done

Completely automated bash to change root password.

Rex5
  • 771
  • 9
  • 23
  • Please format your code correctly using backticks. – BakaKuna Jul 15 '19 at 11:44
  • A different answer proposes to use `expect` for this scenario: https://stackoverflow.com/questions/8236699/script-to-change-password-on-linux-servers-over-ssh – BakaKuna Jul 15 '19 at 11:52

2 Answers2

0

I also think you should use expect. The script I've written isn't fully tested, since I don't have a server which I'm conformable on to change passwords :-)

#!/bin/bash

read -p "Server username? " USERNAME
read -sp "Server password for ${USERNAME}? " PASSWORD

echo
read -p "Name of file containing server list? " S_FILE
read -p "User to change on servers? " S_USERNAME
read -sp "New password for user ${S_USERNAME}?" S_PASSWORD
echo

while IFS= read -r SERVER; do
        [ ! -z "${SERVER}" ] || continue
        expect <<-EOF
                spawn ssh ${USERNAME}@${SERVER}
                expect "*: " { send "${PASSWORD}\r" }
                expect "*$ " { send "echo '${S_USERNAME}:${S_PASSWORD}' | sudo chpasswd\r" }
                expect "*: " { send "${PASSWORD}\r" }
                expect "*$ " { send "exit\r" }
EOF
        echo
done < ${S_FILE}
exit $?
Bayou
  • 3,293
  • 1
  • 9
  • 22
0

Writing a script to do unattended root things is dangerous. All you need is one machine to somehow behave differently than you expect and your automated approach wouldn't work. Worse, you could end up in some bad state, possibly without even realizing that anything went wrong.

This sounds like a great fit for csshx (or something similar). Use it to manually apply whatever changes you want in parallel across multiple hosts. For example, you could connect to 16 hosts at once like this:

csshx host[1-16]

then type commands and watch output for each host.

If this seems infeasible due to the number of machines you have, I would counter that it's much safer than scripting, and - even if "slow" - the overall time spent might very well be less than that of trying to create an automated solution. ;)

Kaan
  • 5,434
  • 3
  • 19
  • 41