Changing Router Passwords via Perl

This article is being posted in answer to a question on my Mikrotik Mailing List. The original poster asked if there was a solution for changing the password on a group of routers. This is something that I have been doing with perl for a VERY long time. Here is the script I have been using.


First, the code:

#!/usr/bin/perl

# Update multiple mikrotiks
# change password script
# Copyright (C) 2004 Butch Evans
# butche@butchevans.com

#########################
# Configuration section #
#########################
# The username and password file with connection information
# to connect to your router.  This user MUST have read and write permissions
# Each line in this file is in the format:
#  routerip::user::userpassword
my $passwdfile = “passwdlist.cfg”;

# If you want to see some output, set this to “1”
my $debug = 1;

# Set the NEW password here
my $newpass = “newpass”;

#############################
# End configuration section #
#############################
# You do not need to change anything below here
# unless you know what you are doing

use strict;
use Net::Telnet ();

# Grab the hosts file (with passwords)
if (! ( -f $passwdfile ) ){
print “ERROR: Password file $passwdfile does not exist!\n\n”;
die;
}

# Slurp the script file into memory
open (PASSWDLIST,$passwdfile);
my @hostlist = ;
close(PASSWDLIST);

my $hostline;
my $host;
my $username;
my $passwd;

#Now, we just cycle through the list of hosts
foreach $hostline (@hostlist){
chomp $hostline;
($host,$username,$passwd) = split(“::”,$hostline);
# Login to the server
if ($debug){
print “Connecting to “. $host .”…”;
}
my $t = new Net::Telnet (Host => $host);
$t->errmode( sub { print “ERROR:” . join(‘|’, @_) . “\n”; } );
$t->login($username, $passwd);
my $errormsg = $t->errmsg;
if ( $errormsg ne “”) {
next; }
# DO THE WORK
my @changepass = $t->cmd(“/user set “. $username .” password=”. $newpass);
if ($debug) {
print “Password change successful\n”;
}
$t->close;
}
exit;

To create the passwdlist.cfg file, you use one line per router with the format:
RouterIP::Username::UserPassword

Like this:
192.168.1.1::admin::adminpass
192.168.1.2::admin::adminpass

That’s all there is to it!   The above code is a GREAT shell for the MANY things you can automate with perl and the Net::Telnet module.  For example, if you wanted to make this script do something else, all you need to do is change the section with the line under “DO THE WORK” comment.  Hope this helps.

Leave a Reply

You must be logged in to post a comment.