20081023 remotely setting unix account passwords - plembo/onemoretech GitHub Wiki

title: Remotely setting Unix account passwords link: https://onemoretech.wordpress.com/2008/10/23/remotely-setting-unix-account-passwords/ author: lembobro description: post_id: 438 created: 2008/10/23 14:06:14 created_gmt: 2008/10/23 14:06:14 comment_status: open post_name: remotely-setting-unix-account-passwords status: publish post_type: post

Remotely setting Unix account passwords

Here is a script that combines the use of Perl’s Net::SSH::Perl with the Linux chpasswd command in order to set a bunch of Unix account passwords from a list.

That list is a simple .csv file with the fields:

TargetServer,UserName,NewPassword

The script handles the routine task of reformatting the UserName and NewPassword string to the “username:password” string needed by chpasswd.

Also notice how I use an “echo” to push that string into the pipe that hands it over to chpasswd.

There’s a log generated to note both success and failure. Although there are other ways to do it, I’ve come to favor using eval for exception handling in scripts like this.

Of course this requires that you know the root password on the target server(s). If it’s different on each server, you’d need to accommodate that with some additional code.

Pretty simple, right? Here’s the program listing:

`

#!/usr/bin/perl
use strict;
use Net::SSH::Perl;
use Text::ParseWords;
	
my $adminuser = "root";
my $adminpass = "********";
	
my $HOME = $ENV{'HOME'};
	
my $errfile = "$HOME/test-users.log";
my $infile = "$HOME/test-users.csv";
	
open LOGZ, ">$errfile" or die $!;
open FH, "<$infile" or die $!;
	
my $time = localtime();
	
print "$time Begin password changesn";
	
while () {
  chomp;
	
  my (
     $target,
     $username,
     $userpass
	
  ) = ( &parse_line(’,',0,$_));
	
  my $userstr = $username . “:” . $userpass;
	
  print $target, ” “, $userstr, “n”;
	
  my $ssh = Net::SSH::Perl->new($target);
	
  eval {
    $ssh->login($adminuser, $adminpass);
  };
  if( $@ ) {
	
  print “t$target root auth failed!n”;
  print LOGZ “t$target root auth failed!n”;
  next;
  }
  else {
	
   my $cmd = “echo $userstr | /usr/sbin/chpasswd”;
	
  eval {
      my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
  };
  if ( $@ ) {
    print “t$target $username password change failedn”;
    print LOGZ “t$target $username password change failedn”;
   # print $stdout, “n”;
    next;
  }
  else {
    print “t$target $username password changedn”;
    print LOGZ “t$target $username password changedn”;
  }
 }
}
close FH;
close LOGZ;
	
__END__;

`

Any IT managers reading this who have a data center with more than 10 or 20 servers should ask themselves the question, “Do we have anything like this to do mass password resets?” If not, ask yourself, “why not?”

Copyright 2004-2019 Phil Lembo