Setting root password remotely of Linux Machines using Expect & Bash

The requirement came to is to set root password of numerous Linux machines. One think thankfully there was , it was only required for root user.

One way round is to manually login each and every machine and set root password, which is never a System Administrator cup of Tea. Another way out is to automate the tasks, Ansible/Puppet can help here but again we have to do one time work for each machine, which again is a tedious task.

There can be several other ways suggested by different admins as per their Experience, for me EXPECT has done the trick (beneficially, it only has to be installed on one machine, from where i have to login and run the script to change root passwords of remote client.

Expect is a program that “talks” to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be.

In general, Expect is useful for running any program which requires interaction between the program and the user. In simple words, its like automating your interactive tasks in a script.

Setup: Testing script on 2 machines first

Server: desktop6  – 192.168.16.10  

Client1: controller – 192.168.16.50 – current password “redhat”              

Client2: compute – 192.168.16.60 – current password “redhat13”

ServerIP and current password are picked from different files:

/var/tmp/hosts.txt    &     /var/tmp/password.txt

page1

Now next target was to feed both file values in a loop, here other admins might have different view than mine, but using for/while loop was over complicating the script structure, so i use paste function:

page2

So testing this script is successfully feeding the inputs

page3

Now for actual implementation of task, let’s comment this echo line in script and un-comment actual script line starting with /var/tmp/changing_root_password.sh line above it, which is our actual expect script.

Now the expect script called in above bash script server the purpose:

Note: [ Currently script is getting stuck for machines, which are present in our known hosts, We will fix this later. As a workaround, please clean by following on server where you are performing this script: # >.ssh/known_hosts ]

page4

Before checking its actual implementation, lets learn a bit about this script:

spawn: its helps in feeding actual command, by default it echoes the command feeded, so we used -noecho flag to suppress the command echo itself. 

NOTE: [ In order to avoid putting same password twice, we use this stdin transcript. ]

lindex: Grabbing here a variable from the command line of the expect script and setting it to a variable.

expect: It will ask for expected pattern.

send: It will tell what actual value to give in response.

Now let’s test this script:

page3

Hurray, our script successfully updated the values.

Leave a comment