Tuesday, November 15, 2011

Script for Resetting Root Password in Multiple Linux servers

OS: CentOS, Redhat
Scripting language: Perl
Perl module required: Net::SSH::Expect

What you need to do? 

In server where the perl script will be executed, create a file "serverlist.txt" and add the server ip address line by line.


Script is as below

use Net::SSH::Expect;

$oldpass = $ARGV[0];
$newpass = $ARGV[1];
chomp $newpass;

sub connect($$)
        chomp $server;
        chomp $password;
        $ssh = Net::SSH::Expect->new (
                host => $server,
                password=> $password,
                user => 'root',
                raw_pty => 1,
                timeout => 30

sub login($)
        eval {  $login_output = $ssh->login(); };  if ($@) {print "$server not found\n"; next; };
                if ($login_output !~ /Last/) {
                        print "Login password error for server $server , please enter the password: ";
                        $inputpass = <STDIN>;
                else {
        #               &resetpass();
        $ssh->waitfor(':\s*\z', 10) or warn "$server - Error 'New password:' prompt not found\n";
        $ssh->waitfor(':\s*\z', 10) or warn "$server - Error 'Confirm new password:' prompt not found\n";
        $ssh->waitfor('#\s*\z', 10) or warn "$server - Error 'Prompt not found after reset:'\n";
        print "$server new password is \t $newpass\n";

open (SERV,"serverlist.txt") || die "ERROR: Unable to open Serverlist file $! \n";
while ( $ip = <SERV> ) {
sleep 2;

Running the script

./passwordreset.pl <Oldpassword> <Newpassword> 

The script will automatically login to the listed servers and reset the root password 

1 comment:

  1. All three chomp()s are superfluous.
    You are leaving a sub using 'next', that should be a 'return'.
    The & is not necessary in &connect()