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.
Eg:
192.168.0.1
192.168.0.2
Script is as below
#!/usr/bin/perl
use Net::SSH::Expect;
$oldpass = $ARGV[0];
$newpass = $ARGV[1];
chomp $newpass;
sub connect($$)
{
$password=shift;
$server=shift;
chomp $server;
chomp $password;
$ssh = Net::SSH::Expect->new (
host => $server,
password=> $password,
user => 'root',
raw_pty => 1,
timeout => 30
);
&login($ssh)
}
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>;
&connect($inputpass,$ip)
}
else {
# &resetpass();
$ssh->send("passwd");
$ssh->waitfor(':\s*\z', 10) or warn "$server - Error 'New password:' prompt not found\n";
$ssh->send("$newpass");
$ssh->waitfor(':\s*\z', 10) or warn "$server - Error 'Confirm new password:' prompt not found\n";
$ssh->send("$newpass");
$ssh->waitfor('#\s*\z', 10) or warn "$server - Error 'Prompt not found after reset:'\n";
print "$server new password is \t $newpass\n";
$ssh->close();
}
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.
Eg:
192.168.0.1
192.168.0.2
Script is as below
#!/usr/bin/perl
use Net::SSH::Expect;
$oldpass = $ARGV[0];
$newpass = $ARGV[1];
chomp $newpass;
sub connect($$)
{
$password=shift;
$server=shift;
chomp $server;
chomp $password;
$ssh = Net::SSH::Expect->new (
host => $server,
password=> $password,
user => 'root',
raw_pty => 1,
timeout => 30
);
&login($ssh)
}
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>;
&connect($inputpass,$ip)
}
else {
# &resetpass();
$ssh->send("passwd");
$ssh->waitfor(':\s*\z', 10) or warn "$server - Error 'New password:' prompt not found\n";
$ssh->send("$newpass");
$ssh->waitfor(':\s*\z', 10) or warn "$server - Error 'Confirm new password:' prompt not found\n";
$ssh->send("$newpass");
$ssh->waitfor('#\s*\z', 10) or warn "$server - Error 'Prompt not found after reset:'\n";
print "$server new password is \t $newpass\n";
$ssh->close();
}
}
open (SERV,"serverlist.txt") || die "ERROR: Unable to open Serverlist file $! \n";
while ( $ip = <SERV> ) {
sleep 2;
&connect($oldpass,$ip);
}
Running the script
./passwordreset.pl <Oldpassword> <Newpassword>
The script will automatically login to the listed servers and reset the root password
All three chomp()s are superfluous.
ReplyDeleteYou are leaving a sub using 'next', that should be a 'return'.
The & is not necessary in &connect()