Router Wi-Fi Password Change & Display V5

:warning: :skull_crossbones: :exclamation: WARNING :exclamation: :skull_crossbones: :warning: USE AT YOUR OWN RISK

Using this Setup without fully understanding how it works can brick your Router, rendering it inoperable, which is difficult or impossible to recover from. This setup runs Shell Commands directly on your Router which almost certainly is a violation of the manufacturers warranty.

You have been warned !!!

:warning: :skull_crossbones: :exclamation: WARNING :exclamation: :skull_crossbones: :warning: USE AT YOUR OWN RISK


V5 of the WiFi Password Change method leverages features available in SambaPOS V5 including Task Types, Reporting, JScript, and GraphQL.

  • Using Task Types, we can record password change history,

  • Using Reporting, we can read that history.

  • Using JScript, we have much improved error trapping and logging, and we can simplify the BAT file significantly by removing the unnatural and cryptic methods of error checking.

  • Using GraphQL in JS, we can manipulate the Task Types in a more natural manner.

Quick Links:

Using PuTTY, PLINK, and PUTTYGEN:

How the Script Works


##LOG:

A sample of the log produced.


==================================================================

--- WIFI PW Change BEG ---------- 2017-05-16 00:18:43.347
NAME    : RouterSOLAZ
HOST    : 192.168.1.1
PORT    : 22
TYPE    : Asus RT-AC66U
FIRM    : AsusMerlin-WRT
KEYFILE : NO
BATFILE : WIFIexec.bat

Current Passwords ----------
wl0.1_wpa_psk=rtrtrtrt
wl0.2_wpa_psk=
wl0.3_wpa_psk=
wl1.1_wpa_psk=rtrtrtrt
wl1.2_wpa_psk=
wl1.3_wpa_psk=


Setting Password wl0.1_wpa_psk=vbvbvbvb ----------

Setting Password wl1.1_wpa_psk=vbvbvbvb ----------

Commit ----------

New Passwords ----------
wl0.1_wpa_psk=vbvbvbvb
wl0.2_wpa_psk=
wl0.3_wpa_psk=
wl1.1_wpa_psk=vbvbvbvb
wl1.2_wpa_psk=
wl1.3_wpa_psk=


Restarting (service restart_wireless) ----------
Done.


SUCCESS
--- WIFI PW Change END ---------- 2017-05-16 00:19:00.157
1 Like

##Task Type

##WiFi (Task Type)##

Name: WiFi
Field Name Field Type Editing Format Display Format
rNameString
rHostString
rTypeString
rFirmwareString
pw1String
pw2String
pw3String

##Report

##WIFI Tasks [0] (Report)##

Report Name: WIFI Tasks
Page Size: 20cm
Display in Report Explorer: checked
Visual Printing: unchecked

Template:

[WiFi Tasks:1,2, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1]
>|CURRENT|{REPORT TASK DETAILS:TSC.pw1:T.Completed==False && (TST=WiFi)}

>>Type|Name|rName|rHost|rType|rFW|pw1|isComplete|dStart|tStart|dEnd|tEnd
{REPORT TASK DETAILS:T.TaskType,T.Name,TSC.rName,TSC.rHost,TSC.rType,TSC.rFirmware,TSC.pw1,T.Completed,T.StartDate,T.StartTime,T.EndDate.desc,T.EndTime.desc:T.Completed==False && (TST=WiFi)}
 
>>Previous
>>Type|Name|rName|rHost|rType|rFW|pw1|isComplete|dStart|tStart|dEnd|tEnd
{REPORT TASK DETAILS:T.TaskType,T.Name,TSC.rName,TSC.rHost,TSC.rType,TSC.rFirmware,TSC.pw1,T.Completed,T.StartDate,T.StartTime,T.EndDate.desc,T.EndTime.desc:T.Completed==True && (TST=WiFi)}

Sample Output:

##Script

The Jscript functions contain a lot of variables at the very top that you need to set. Most of them are self-explanatory.

The script also supports running a simple BAT file or a more complex BAT file. By default, the simple BAT file is preferred and used, and code for the complex BAT file is disabled (commented out).


Name: WiFi
Handler: wifi
Script:

var nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

var minPWlength = 8;

// BAT file settings, the BAT file and PLINK should be in the same Path
var batDrive = 'D:';
var batPath  = "D:/Programs/POS/router/";
var batFile  = "WIFIchange.bat"; // complex BAT
	batFile  = 'WIFIexec.bat';   // simple BAT
var batLog   = "WIFIchange.txt";
var batRes   = "WIFIresult.txt";
var batHidden = true;

// ROUTER setings
var rHost = '192.168.1.1';
var rPort = '22';

// these settings are arbitrary, but are used as part of the Task Name and Identifier
var rName = 'RouterJV';
var rType = 'Trendnet TEW812DRU';

// router firmware dictates which commands to issue in the BAT file
var rFirmware = 'AsusMerlin-WRT'; // restart wireless service
var rFirmware = 'DD-WRT'; // reboot the router

// generally, the username via SSH for DD-WRT firmware is 'root', while other firmware uses 'admin'
var rUser = rFirmware=='DD-WRT' ? 'root' : 'admin';

// we can use a Password or Keyfile to login to the Router
var rPass = 'myrouterpassword';
var rKey  = 'myrouterprivatekey.ppk';


// Task Default parameters
var userName = 'Admin';
var taskType = 'WiFi';
var taskName = '';
var ident = ''
var isCompleted = '';
var customData = [];
var content = '';
var state = '';

// updates WiFi Task
function setPW(pw) {

	// get current PW from DB
	var SQL = "SELECT [Id],[Name],[Value] FROM [ProgramSettingValues] WHERE [Name]='WiFiPW'";
	var res = sql.Exec(SQL);
	var	wifipwDB = res[0].split(',');
		wifipwDB = wifipwDB[2];
	
	// check input parm for value
	pw = typeof(pw)=='undefined' || pw=='' ? wifipwDB : pw;
	
	// check PW length
	if (pw.length < minPWlength) {
		var errmsg = "!!! ERROR !!!\r\nPassword is less than "+minPWlength+" characters!";
		throwError('setPW',taskType,taskName,ident,errmsg,true);
		return -1;
	}
	
	// check PW for illegal characters
	var iChars = '{}[]:;=$%&*';
	for (var c=0; c<iChars.length; c++) {
		var foundChar = pw.indexOf(iChars[c]) > -1 ? true : false;
		if (foundChar) {
			var errmsg = "!!! ERROR !!!\r\nPassword contains illegal character: '"+iChars[c]+"'";
			throwError('setPW',taskType,taskName,ident,errmsg,true);
			return -1;
			break;
		}
	}
	
	//dlg.ShowMessage("Changing Password to:\r\n"+pw);


	
	// execute Router commands -- simple BAT
	// this is the PREFERRED method since it is easier to parse and handle results or errors in JS than in BAT
	var batResult = execRouter(pw,rHost,rPort,rUser,rPass,rKey,rFirmware,batDrive,batPath,batLog,batRes);
	if (batResult != 0) {
		return -1;
	}


	/*
	// execute BAT file -- complex BAT
	// this is NOT the preferred method since it is much more difficult to parse and handle results or errors in BAT files than it is in JS
	var batResult = execBAT(pw,rHost,rPort,rUser,rPass,rKey,rFirmware,batDrive,batPath,batLog,batRes);
	if (batResult != 0) {
		return -1;
	}
	*/
	


	// if Router Commands were executed without errors, then update Task data
	
	// get incomplete Tasks
	isCompleted = 'false';
	var wifi = gqlEXEC(getTasks(taskType,isCompleted));
	//return wifi;
	// {"data":{"tasks":[]}}
	// {"data":null,"errors":[{"message":"Error trying to resolve getTasks.","locations":[{"line":0,"column":0}]}]}
	wifi = JSON.parse(wifi);

	if (wifi.errors) {
		var errmsg = "!!! ERROR !!!\r\ngetTasks()\r\n" + wifi.errors[0].message;
		throwError('setPW',taskType,taskName,ident,errmsg,true);
		return -1;
	}
	
	
	
	// complete previous (incomplete) Tasks
	var taskCount = wifi.data.tasks.length;
	if (taskCount > 0) {
		isCompleted = 'true';
		for (var t=0; t<taskCount; t++) {
			var cident  = wifi.data.tasks[t].identifier;
			var wifi = gqlEXEC(updateTaskByIdentifier([taskType], [cident], isCompleted));
		}
	}



	// add NEW Task
	var pw1 = pw;
	var pw2 = pw;
	var pw3 = pw;

	taskName = rName + ' ' + rType + ' ' + rHost;
	ident    = taskName.replace(/ /g,'_') + '_' + nowDate;
	isCompleted  = '';
	customData   = [];
	customData.push({name:"Id",value:ident});
	customData.push({name:"rName",value:rName});
	customData.push({name:"rHost",value:rHost});
	customData.push({name:"rType",value:rType});
	customData.push({name:"rFirmware",value:rFirmware});
	customData.push({name:"pw1",value:pw1});
	customData.push({name:"pw2",value:pw2});
	customData.push({name:"pw3",value:pw3});

	isCompleted = 'false';
	var wifi = gqlEXEC(addTasks([taskType],[taskName],isCompleted,customData,userName));
	
	// set current PW in DB
	var SQL = "UPDATE [ProgramSettingValues] SET [Value]='"+pw+"' WHERE [Name]='WiFiPW'";
	var res = sql.Exec(SQL);

	// execute Automation Command for any post-process Actions
	cmd.Execute('WIFI Update Password RESULT:0');

	return 0;
}

function execRouter(pw,rHost,rPort,rUser,rPass,rKey,rFirmware,batDrive,batPath,batLog,batRes) {

	// this function executes a very simple BAT file that invokes PLINK to run commands on the Router
	
	// 2.4 GHz band, passwords for networks 1-3
	var pw24_1=pw;
	var pw24_2=pw;
	var pw24_3=pw;
	
	// 5.0 GHz band, passwords for networks 1-3
	var pw50_1=pw;
	var pw50_2=pw;
	var pw50_3=pw;

	// array of error keywords
	var rErrors = ['ERROR','denied','refused'];
	
	// 2.4 GHz band, NVRAM network variables for networks 1-3
	var rGUEST24net1="wl0.1_wpa_psk";
	var rGUEST24net2="wl0.2_wpa_psk";
	var rGUEST24net3="wl0.3_wpa_psk";
	
	// 5.0 GHz band, NVRAM network variables for networks 1-3
	var rGUEST50net1="wl1.1_wpa_psk";
	var rGUEST50net2="wl1.2_wpa_psk";
	var rGUEST50net3="wl1.3_wpa_psk";

	// commands to show current passwords, commit changes, restart, and reboot
	var cShowNets="nvram show | grep wl..._wpa_psk | sort | sed 's/wl/\\r\\nwl/g'";
	var cCommitNVRAM="nvram commit";
	var cRESTARTwifi="service restart_wireless";
	var cREBOOT="reboot";
	
	// 2.4 GHz band commands for setting passwords for networks 1-3
	var cSetNet24_1="nvram set "+rGUEST24net1+"="+pw24_1;
	var cSetNet24_2="nvram set "+rGUEST24net2+"="+pw24_2;
	var cSetNet24_3="nvram set "+rGUEST24net3+"="+pw24_3;
	
	// 5.0 GHz band commands for setting passwords for networks 1-3
	var cSetNet50_1="nvram set "+rGUEST50net1+"="+pw50_1;
	var cSetNet50_2="nvram set "+rGUEST50net2+"="+pw50_2;
	var cSetNet50_3="nvram set "+rGUEST50net3+"="+pw50_3;


	// check to verify batFile exists
	var batcheck = file.ReadFromFile(batPath+batFile);
		batcheck = batcheck.length < 10 ? false : true;

	// check to verify Key File exists
	var keyfile = file.ReadFromFile(batPath+rKey);
	var bKey = keyfile.length < 500 ? "NO" : rKey;



	// build array of commands that we want to execute
	var batParms = [];
	var batSteps = [];
	
	var commonParms = bKey+" "+rHost+" "+rPort+" "+rUser+" "+rPass+" "+batDrive+" "+batPath+" "+batRes;
	
	batSteps.push("Current Passwords");
	batParms.push(commonParms +" "+'"'+cShowNets+'"');
	
	batSteps.push("Setting Password "+rGUEST24net1+"="+pw24_1);
	batParms.push(commonParms +" "+'"'+cSetNet24_1+'"');
	
	batSteps.push("Setting Password "+rGUEST50net1+"="+pw50_1);
	batParms.push(commonParms +" "+'"'+cSetNet50_1+'"');
	
	batSteps.push("Commit");
	batParms.push(commonParms +" "+'"'+cCommitNVRAM+'"');
	
	batSteps.push("New Passwords");
	batParms.push(commonParms +" "+'"'+cShowNets+'"');
	
	batSteps.push("Restarting ("+(rFirmware=='DD-WRT' ? cREBOOT : cRESTARTwifi)+")");
	batParms.push(commonParms +" "+'"'+(rFirmware=='DD-WRT' ? cREBOOT : cRESTARTwifi)+'"');
	


	// start logging
	var filewrite = file.AppendToFile(batPath+batLog,"\r\n==================================================================\r\n\r\n");

	var filewrite = file.AppendToFile(batPath+batLog,"--- WIFI PW Change BEG ---------- "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"NAME    : "+rName+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"HOST    : "+rHost+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"PORT    : "+rPort+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"TYPE    : "+rType+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"FIRM    : "+rFirmware+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"KEYFILE : "+bKey+"\r\n");
	var filewrite = file.AppendToFile(batPath+batLog,"BATFILE : "+batFile+"\r\n\r\n");
	
	if (!batcheck) {
		var errmsg = 'batFile ['+batPath+batFile+'] does not exist!';
		var filewrite = file.AppendToFile(batPath+batLog,errmsg+"\r\n");
		throwError('execRouter() ['+batResult+']',taskType,taskName,ident,errmsg,true);
		return -1;
	}

	// execute the BAT file using batParms[] array
	for (var p=0; p<batParms.length; p++) {
		if (batHidden) {
			var batResult = file.Starter(batPath+batFile).With(batParms[p]).WorkOn(batPath).Hidden.ShellExecute();
		} else {
			var batResult = file.Starter(batPath+batFile).With(batParms[p]).WorkOn(batPath).ShellExecute();
		}
		
		// the BAT file directs results for each command to a Result File, so we read it to find out what happened and check for errors
		var opres = file.ReadFromFile(batPath+batRes);
			opres = opres.split("\r\n");
			
		// build some output to append to the Log
		var lines = '';
		for (var o=0; o<opres.length; o++) {
			// get rid of empty lines in the Result file, and clean some garbage
			lines += opres[o]=='' || (opres[o].indexOf('size') > -1) ? '' : opres[o].replace(' bytes ','').replace(' left','').replace(/\([0-9]+\)/g,'') + "\r\n";
		}
		
		// write info to the Log, including the Step and cleaned Result File content
		var filewrite = file.AppendToFile(batPath+batLog,batSteps[p]+" ----------\r\n");
		var filewrite = file.AppendToFile(batPath+batLog,lines+"\r\n\r\n");
		
		// iterate error keywords array to check if our Result File contained any errors and terminate the process if any errors found
		for (var e=0; e<rErrors.length; e++) {
			if (lines.indexOf(rErrors[e]) > -1) {
				var filewrite = file.AppendToFile(batPath+batLog,"FAILED\r\n")
				var filewrite = file.AppendToFile(batPath+batLog,"--- WIFI PW Change END ---------- "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+"\r\n");
				throwError('execRouter() ['+batResult+']',taskType,taskName,ident,lines,true);
				return -1;
			}
		}
	}
	
	// if everything executed properly, Log the Success
	var filewrite = file.AppendToFile(batPath+batLog,"SUCCESS\r\n")
	var filewrite = file.AppendToFile(batPath+batLog,"--- WIFI PW Change END ---------- "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+"\r\n");

	return 0;
}

function execBAT(pw,rHost,rPort,rUser,rPass,rKey,rFirmware,batDrive,batPath,batLog,batRes) {

	// this function executes a somewhat complex BAT file that invokes PLINK to run commands on the Router
	// error checking and logging is all handled in the BAT file

	var batParms = pw+' '+rHost+' '+rPort+' '+rUser+' '+rPass+' '+rKey+' '+rFirmware+' '+batDrive+' '+batPath+' '+batLog+' '+batRes;
	
	var batResult = file.Starter(batPath+batFile).With(batParms).WorkOn(batPath).ShellExecute();

	if (batResult != 0) {
		var errmsg = file.ReadFromFile(batPath+batRes);
		throwError('WIFIchange.bat ['+batResult+']',taskType,taskName,ident,errmsg,true);
		return -1;
	}
	
	return 0;
}


function throwError(func,taskType,taskName,taskIdent,parm,halt) {

	// function to handle errors in a common manner
	
	func = typeof(func)==='undefined' || func=='' ? 'unknown' : func;
	taskType = typeof(taskType)==='undefined' || taskType=='' ? 'unknown' : taskType;
	taskName = typeof(taskName)==='undefined' || taskName=='' ? 'unknown' : taskName;
	taskIdent = typeof(taskIdent)==='undefined' || taskIdent=='' ? 'unknown' : taskIdent;
	parm = typeof(parm)==='undefined' || parm=='' ? 'unknown' : parm;
	halt = typeof(halt)==='undefined' || halt=='' ? true : halt;

	var errmsg = 'ERROR in '+func;
	errmsg += "\r\n"+'taskType: '+taskType;
	errmsg += "\r\n"+'taskName: '+taskName;
	errmsg += "\r\n"+'taskIdent: '+taskIdent;
	errmsg += "\r\n"+'parm: '+parm;
	errmsg += "\r\n"+'halt: '+halt;
	
	//dlg.AskQuestion('<size 12><font Consolas>'+errmsg+'</font></size>',"Ok");

	// execute Automation Command for any post-process Actions
	cmd.Execute("WIFI Update Password RESULT:"+errmsg);

	return -1;
}




// main GraphQL Execute Function
function gqlEXEC(query, callback) {
	//return query;
    var data = gql.Exec(query);  // returns JSON as String
    var dobj = JSON.parse(data); // converts JSON String to Object
    return data;
};

// Query for addTasks
function addTasks(taskTypes,taskNames,isCompleted,customData,userName,content,state) {
    var q = '';
        q+= 'mutation m{';
        for (var t=0; t<taskNames.length; t++) {
            var taskType = taskTypes[t];
            var taskName = taskNames[t];
            q += 'm'+t+': ';
            q+= 'addTask(';
            q+= 'task:{';
            q+= 'taskType:"'+taskType+'"';
            q+= ',name:"'+taskName+'"';
            q+= ',isCompleted:'+isCompleted;
            q+= ',userName:"'+userName+'"';
            q+= typeof(content)==='undefined' ? '' : ',content:' + '"'+content+'"';
            q+= typeof(state)==='undefined' ? '' : ',state:' + '"'+state+'"';
            q+= ',customData:[';
            if (customData) {
                for (var d=0; d<customData.length; d++) {
                    q+= (d==0 ? '' : ',');
                    q+= '{name:"'+customData[d].name+'",value:"'+customData[d].value+'"}';
                }
            }
            q+= ']';
            q+= '}';
            q+= ')';
            q+= '{id,name,identifier,content,isCompleted,userName,customData{name,value}}';
            q += ((t+1) != taskNames.length ? ', ' : '');
        }
        q+= '}';
    return q;
};

// Query for getTasks
function getTasks(taskType, completedFilter, nameLike, startFilter, endFilter, contentLike, fieldFilter, stateFilter, callback) {
    var q = '';
        q+= '{tasks:getTasks(';
        q+= 'taskType:"'+taskType+'"';
        q+= (startFilter ? ',startDate:"'+startFilter+'"' : '');
        q+= (endFilter ? ',endDate:"'+endFilter+'"' : '');
        q+= (completedFilter!='' ? ',isCompleted:'+completedFilter : '');
        q+= (nameLike ? ',nameLike:"'+nameLike+'"' : '');
        q+= (contentLike ? ',contentLike:"'+contentLike+'"' : '');
        q+= (stateFilter ? ',state:"'+stateFilter+'"' : '');
        q+= (fieldFilter ? ',customFields:[{name:"'+fieldFilter.name+'",value:"'+fieldFilter.value+'"}]' : '');
        q+= ')';
        q+= '{id,isCompleted,identifier,name,state,content,contentText,customData{name,value},stateLog{state,start,end},stateDuration{state,duration},startDate,endDate,userName}';
        q+= '}';
    return q;
};

// Query for updateTask (by identifier and taskType)
function updateTaskByIdentifier(taskTypes, taskIdents, isCompleted, taskName, customData, content, state){
    var q = 'mutation m {';
    for (var t=0; t<taskIdents.length; t++) {
        var taskIdent = taskIdents[t];
        var taskType = taskTypes[t];
        q += 'm'+t+': updateTask(';
        q += 'identifier:"'+taskIdent+'"';
        q += ', taskType:"'+taskType+'"';
        q += ', task:{';
        q += 'taskType:"'+taskType+'"';
        q += (isCompleted!='' ? ',isCompleted:'+isCompleted : '');
        q += (taskName ? ', name:"'+taskName+'"' : '');
        q += content ? ',content:"'+content+'"' : '';
        q += state ? ',state:"'+state+'"' : '';
        q += ',customData:[';
        if (customData) {
            for (var d=0; d<customData.length; d++) {
                q+= (d==0 ? '' : ',');
                q+= '{name:"'+customData[d].name+'",value:"'+customData[d].value+'"}';
            }
        }
        q+= ']';
        q += '}';
        q += ')';
        q+= '{id,isCompleted,identifier,name,state,content,contentText,customData{name,value},stateLog{state,start,end},stateDuration{state,duration},startDate,endDate,userName}';
        //q += '}';
        q += ((t+1) != taskIdents.length ? ', ' : '');

    }
    	q += '}';
    return q;
};

#BAT Files

This Setup can use 1 of 2 BAT files. You don’t need both. The simple BAT file is preferred.

##BAT (simple)

This is the preferred BAT file.

Name: WIFIexec.bat

CLS

@%8
CD %9

set USEKEY=%1

IF "%USEKEY%" EQU "NO" plink.exe -ssh %2 -P %3 -l %4 -pw %5 -batch %6 > %7 2>&1

IF "%USEKEY%" NEQ "NO" plink.exe -ssh %4@%2 -P %3 -i %1 -batch %6 > %7 2>&1

##BAT (complex)

This is NOT the preferred BAT file.

Name: WIFIchange.bat

@echo off
cls

:: var batParms = pw+' '+rHost+' '+rPort+' '+rUser+' '+rPass+' '+rKey+' '+rFirmware+' '+batDrive+' '+batPath+' '+batLog+' '+batRes;
::                %1     %2        %3        %4        %5        %6       %7            %8           %9          %10        %11

::
:: Set variables for new passwords (get the %1 argument and use it for all networks)
::
set newpass=%1

::
:: Set Router Information
::
set rHOST=%2
set rPORT=%3
set rUSER=%4
set rPASS=%5
set rKEY=%6
set FW=%7
set bDRIVE=%8
set bPATH=%9

:: shift 2 times to get parms 10 and 11
shift
shift

::
:: Set a LOGFILE and ERRMSG
::
set LOGFILE=%8
set ERRMSG=
set RESFILE=%9

::
:: Set WiFi Network Information as found in NVRAM
::
set rGUEST24net1=wl0.1_wpa_psk
set rGUEST24net2=wl0.2_wpa_psk
set rGUEST24net3=wl0.3_wpa_psk
set rGUEST50net1=wl1.1_wpa_psk
set rGUEST50net2=wl1.2_wpa_psk
set rGUEST50net3=wl1.3_wpa_psk


echo %LOGFILE%
echo %RESFILE%

::
:: Go to PLINK location
::
@%bDRIVE%
CD %bPATH%


set USEKEY=NO
IF EXIST %rKEY% SET USEKEY=YES

set REBOOT=NO
IF "%FW%" EQU "DD-WRT" set REBOOT=YES


::
:: Set variables for new passwords (get the %1 argument and use it for all networks)
::
set pw24_1=%newpass%
set pw24_2=%newpass%
set pw24_3=%newpass%
set pw50_1=%newpass%
set pw50_2=%newpass%
set pw50_3=%newpass%


::
:: Set up Commands
::
set cShowNets="nvram show | grep wl..._wpa_psk | sort | sed 's/wl/\r\nwl/g'"
set cCommitNVRAM="nvram commit"
set cRESTARTwifi="service restart_wireless"
set cREBOOT="reboot"
set cSetNet24_1="nvram set %rGUEST24net1%=%pw24_1%"
set cSetNet24_2="nvram set %rGUEST24net2%=%pw24_2%"
set cSetNet24_3="nvram set %rGUEST24net3%=%pw24_3%"
set cSetNet50_1="nvram set %rGUEST50net1%=%pw50_1%"
set cSetNet50_2="nvram set %rGUEST50net2%=%pw50_2%"
set cSetNet50_3="nvram set %rGUEST50net3%=%pw50_3%"


::
:: Show us what we are about to do
::
@echo rHOST: %rHOST%
@echo rPORT: %rPORT%
@echo pw24_1: %pw24_1%
@echo pw50_1: %pw50_1%
@echo USEKEY: %USEKEY%
@echo REBOOT: %REBOOT%


::
:: Start Logging
::
@echo. >> %LOGFILE% 2>&1
@echo ******************************************************* >> %LOGFILE% 2>&1
@echo -- BAT BEG ----------------- %date%_%time:~0,2%.%time:~3,2%.%time:~6,2% >> %LOGFILE% 2>&1

::
:: Run COMMANDS through PLINK
::
::@echo on

:: If we get this far, it's time to run the commands to the Router
@echo -- ROUTER CHANGE BEG ------- %date%_%time:~0,2%.%time:~3,2%.%time:~6,2% >> %LOGFILE% 2>&1
@echo rHOST: %rHOST%>> %LOGFILE% 2>&1
@echo rPORT: %rPORT%>> %LOGFILE% 2>&1
@echo net24_1: %rGUEST24net1%>> %LOGFILE% 2>&1
@echo net50_1: %rGUEST50net1%>> %LOGFILE% 2>&1
@echo pwd24_1: %pw24_1%>> %LOGFILE% 2>&1
@echo pwd50_1: %pw50_1%>> %LOGFILE% 2>&1
@echo.>> %LOGFILE% 2>&1




:: Show CURRENT Passwords
@echo ----- Guest Networks CURRENT ...>> %LOGFILE% 2>&1
::plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cShowNets% >> %LOGFILE% 2>&1
::plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cShowNets% >> %LOGFILE% 2>&1

IF "%USEKEY%" EQU "NO" plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cShowNets% > %RESFILE% 2>&1
IF "%USEKEY%" EQU "YES" plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cShowNets% > %RESFILE% 2>&1

set var1=
set var2=
set var3=
set var4=
set var5=
set var6=
set var7=

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (%RESFILE%) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
IF "%var1%" NEQ "" @echo %var1% >> %LOGFILE%
IF "%var2%" NEQ "" @echo %var2% >> %LOGFILE%
IF "%var3%" NEQ "" @echo %var3% >> %LOGFILE%
IF "%var4%" NEQ "" @echo %var4% >> %LOGFILE%
IF "%var5%" NEQ "" @echo %var5% >> %LOGFILE%
IF "%var6%" NEQ "" @echo %var6% >> %LOGFILE%
IF "%var7%" NEQ "" @echo %var7% >> %LOGFILE%
::ENDLOCAL

set PAT=ERROR
echo.%var1% | findstr /C:"%PAT%" 1>nul
if errorlevel 1 (
  @echo Connection processed successfully.
) ELSE (
  set ERRMSG=%var1%
)
set errorlevel=

set PAT=refused
echo.%var1% | findstr /C:"%PAT%" 1>nul
if errorlevel 1 (
  @echo Login processed successfully.
) ELSE (
  set ERRMSG=%ERRMSG% %var1%
)
set errorlevel=

set PAT=denied
echo.%var1% | findstr /C:"%PAT%" 1>nul
if errorlevel 1 (
  @echo ShowNets Command processed successfully.
) ELSE (
  set ERRMSG=%ERRMSG% %var1%
)
set errorlevel=

IF "%ERRMSG%" NEQ "" GOTO ERRORPROCESS

@echo.>> %LOGFILE% 2>&1
@echo.>> %LOGFILE% 2>&1





:: Set the Passwords for the desired Networks and Commit NVRAM
@echo ----- SETTING NEW PASSWORDS ...>> %LOGFILE% 2>&1
:: this line currently sets GuestNetwork #1 for both 2.4GHz and 5.0GHz bands and commits them to NVRAM
:: add more Networks if so desired (i.e. cSetNet24_2), and ensure the cCommitNVRAM command is retained
::plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cSetNet24_1% %cSetNet50_1% %cCommitNVRAM% >> %LOGFILE% 2>&1
::plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cSetNet24_1% %cSetNet50_1% %cCommitNVRAM% >> %LOGFILE% 2>&1

IF "%USEKEY%" EQU "NO" plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cSetNet24_1% %cSetNet50_1% %cCommitNVRAM% > %RESFILE% 2>&1
IF "%USEKEY%" EQU "YES" plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cSetNet24_1% %cSetNet50_1% %cCommitNVRAM% > %RESFILE% 2>&1

set var1=
set var2=
set var3=
set var4=
set var5=
set var6=
set var7=

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (%RESFILE%) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
IF "%var1%" NEQ "" @echo %var1% >> %LOGFILE%
IF "%var2%" NEQ "" @echo %var2% >> %LOGFILE%
IF "%var3%" NEQ "" @echo %var3% >> %LOGFILE%
IF "%var4%" NEQ "" @echo %var4% >> %LOGFILE%
IF "%var5%" NEQ "" @echo %var5% >> %LOGFILE%
IF "%var6%" NEQ "" @echo %var6% >> %LOGFILE%
IF "%var7%" NEQ "" @echo %var7% >> %LOGFILE%
::ENDLOCAL

set PAT=ERROR
echo.%var1% | findstr /C:"%PAT%" 1>nul
if errorlevel 1 (
  @echo SetNets Command processed successfully.
) ELSE (
  set ERRMSG=%var1%
)
set errorlevel=

IF "%ERRMSG%" NEQ "" GOTO ERRORPROCESS

@echo.>> %LOGFILE% 2>&1













:: Show UPDATED Passwords
@echo ----- Guest Networks UPDATED ...>> %LOGFILE% 2>&1
::plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cShowNets% >> %LOGFILE% 2>&1
::plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cShowNets% >> %LOGFILE% 2>&1

IF "%USEKEY%" EQU "NO" plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cShowNets% > %RESFILE% 2>&1
IF "%USEKEY%" EQU "YES" plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cShowNets% > %RESFILE% 2>&1

set var1=
set var2=
set var3=
set var4=
set var5=
set var6=
set var7=

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (%RESFILE%) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
IF "%var1%" NEQ "" @echo %var1% >> %LOGFILE%
IF "%var2%" NEQ "" @echo %var2% >> %LOGFILE%
IF "%var3%" NEQ "" @echo %var3% >> %LOGFILE%
IF "%var4%" NEQ "" @echo %var4% >> %LOGFILE%
IF "%var5%" NEQ "" @echo %var5% >> %LOGFILE%
IF "%var6%" NEQ "" @echo %var6% >> %LOGFILE%
IF "%var7%" NEQ "" @echo %var7% >> %LOGFILE%
::ENDLOCAL

set PAT=ERROR
echo.%var1% | findstr /C:"%PAT%" 1>nul
if errorlevel 1 (
  @echo ShowNets Command processed successfully.
) ELSE (
  set ERRMSG=%var1%
)
set errorlevel=

IF "%ERRMSG%" NEQ "" GOTO ERRORPROCESS

@echo.>> %LOGFILE% 2>&1
@echo.>> %LOGFILE% 2>&1






:: Restart the WIFI Service for new passwords to take effect
@echo ----- RESTARTING WIFI SERVICE ...>> %LOGFILE% 2>&1
::plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cRESTARTwifi% >> %LOGFILE% 2>&1
::plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cRESTARTwifi% >> %LOGFILE% 2>&1

IF "%USEKEY%" EQU "NO" IF "%REBOOT%" EQU "NO" plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cRESTARTwifi% > %RESFILE% 2>&1
IF "%USEKEY%" EQU "NO" IF "%REBOOT%" EQU "YES" plink.exe -ssh %rHOST% -P %rPORT% -l %rUSER% -pw %rPASS% -batch %cREBOOT% > %RESFILE% 2>&1

IF "%USEKEY%" EQU "YES" IF "%REBOOT%" EQU "NO"  plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cRESTARTwifi% > %RESFILE% 2>&1
IF "%USEKEY%" EQU "YES" IF "%REBOOT%" EQU "YES"  plink.exe -ssh %rUSER%@%rHOST% -P %rPORT% -i %rKEY% -batch %cREBOOT% > %RESFILE% 2>&1

set var1=
set var2=
set var3=
set var4=
set var5=
set var6=
set var7=

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (%RESFILE%) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
IF "%var1%" NEQ "" @echo %var1% >> %LOGFILE%
IF "%var2%" NEQ "" @echo %var2% >> %LOGFILE%
IF "%var3%" NEQ "" @echo %var3% >> %LOGFILE%
IF "%var4%" NEQ "" @echo %var4% >> %LOGFILE%
IF "%var5%" NEQ "" @echo %var5% >> %LOGFILE%
IF "%var6%" NEQ "" @echo %var6% >> %LOGFILE%
IF "%var7%" NEQ "" @echo %var7% >> %LOGFILE%
::ENDLOCAL

set PAT=ERROR
echo.%var1% | findstr /C:"%PAT%" 1>nul
if errorlevel 1 (
  IF "%REBOOT%" EQU "NO" @echo Restart WIFI Command processed successfully.
  IF "%REBOOT%" EQU "YES" @echo Reboot Command processed successfully.
) ELSE (
  set ERRMSG=%var1%
)
set errorlevel=

IF "%ERRMSG%" NEQ "" GOTO ERRORPROCESS

@echo.>> %LOGFILE% 2>&1




:: End Router Changes
@echo -- ROUTER CHANGE END ------- %date%_%time:~0,2%.%time:~3,2%.%time:~6,2% >> %LOGFILE% 2>&1

@echo off




::
:: We are almost done. Test for Errors.
::
IF [%ERRMSG%] == [] GOTO finished


:ERRORPROCESS
@echo %ERRMSG% 
@echo %ERRMSG% >> %LOGFILE% 2>&1 
@echo -- BAT END ----------------- %date%_%time:~0,2%.%time:~3,2%.%time:~6,2% >> %LOGFILE% 2>&1
:: Open the LOGFILE
::@notepad %LOGFILE%
exit -1
goto endoffile


:finished
@echo -- BAT END ----------------- %date%_%time:~0,2%.%time:~3,2%.%time:~6,2% >> %LOGFILE% 2>&1


:endoffile
::
:: We are done.  Uncomment the following lines if you wish.
::

::@notepad %LOGFILE%

::timeout 2
::pause

exit 0

##Automation Commands

##WIFI Update Password [Navigation] (Automation Command)##

Name: WIFI Update Password
Category: Navigation
Button Header: WiFi
Color: #FFF79646
Font Size: 26
Confirmation: None
Values (0): (none)
Navigation Settings
Symbol:
Image:
Auto Refresh: 0
Tile Cache: 0
Navigation Module:
Nav Module Parameter:
Template: ``` ? WiFi {SETTING:WiFiPW} ```
Mappings
Terminal User Role Department Ticket Type Enabled States Visible States Visibility
******Display on Navigation

##WIFI Show Password [WiFi and Music] (Automation Command)##

Name: WIFI Show Password
Category: WiFi and Music
Button Header: Show\r((( WiFi )))
Color: #FFFFA500
Font Size: 30
Confirmation: None
Values (0): (none)
Navigation Settings
Symbol:
Image:
Auto Refresh: 0
Tile Cache: 0
Navigation Module:
Nav Module Parameter:
Template: ```

</details>


<details>
<summary><b><u>Mappings</u></b></summary><table><tr><td><b>Terminal</b> </td><td><b>User Role</b> </td><td><b>Department</b> </td><td><b>Ticket Type</b> </td><td><b>Enabled States</b> </td><td><b>Visible States</b> </td><td><b>Visibility</b> </td></tr><tr><td><code>*</code></td><td><code>*</code></td><td><code>*</code></td><td><code>*</code></td><td><code>*</code></td><td><code>*</code></td><td><code>Display under Ticket row 2</code></td></tr></table></details>

##Actions

##WIFI Exec Script [Execute Script] (Action)##

Action Name: WIFI Exec Script
Action Type: Execute Script
###Parameters:###
Function: [:handler.func(parms)]
Command:
Parameters:
Run In Background: [:runBG]

##WIFI Ask Question [Ask Question] (Action)##

Action Name: WIFI Ask Question
Action Type: Ask Question
###Parameters:###
Question: [:question]
Buttons: [:buttons]
Description: [:description]
Automation Command Name: [:AMCname]
Execute Command In Background:
Background Color: [:BGcolor]
Transparent Color: [:TPcolor]
Inactivity Command Name:
Inactivity Timeout Seconds:
Execute Inactivity Command In Background:

##WIFI Update Program Setting [Update Program Setting] (Action)##

Action Name: WIFI Update Program Setting
Action Type: Update Program Setting
###Parameters:###
Setting Name: [:settingName]
Setting Value: [:settingValue]
Update Type: Update
Is Local: False

##Rules

##WIFI Show Password [Automation Command Executed] (Rule)##

Rule Name: WIFI Show Password
Event Name: Automation Command Executed
Rule Tags:
Custom Constraint List (1):
Execute Rule if: Matches
Automation Command NameEqualsWIFI Show Password

##Actions (1):##

WIFI Ask Question

Constraint: (none)

question: Current WiFi Password:\r{SETTING:WiFiPW}
buttons: Ok
description:
AMCname:
BGcolor:
TPcolor:

##WIFI Update Password Prompt and Execute [Automation Command Executed] (Rule)##

Rule Name: WIFI Update Password Get and Check
Event Name: Automation Command Executed
Rule Tags:
Custom Constraint List (1):
Execute Rule if: Matches
Automation Command NameEqualsWIFI Update Password

##Actions (3):##

WIFI Update Program Setting

Constraint: (none)

settingName: WiFiPWold
settingValue: {REPORT TASK DETAILS:TSC.pw1:T.Completed==False && (TST=WiFi)}
WIFI Update Program Setting

Constraint: (none)

settingName: WiFiPWnew
settingValue: [?Enter New WiFi Password (8 characters minimum):([a-zA-Z0-9]{8,26})]
WIFI Exec Script

Constraint: (none)

handler.func(parms): wifi.setPW('{:WiFiPWnew}')
runBG: True

.
.
.
.

:exclamation: The following Rule is optional. It contains Actions that work with my system. You can do whatever you want here, such as including your own Actions, or omit this Rule altogether…

This Rule is fired from the JScript when everything works properly, with a Command Value of 0.

##WIFI Update Password RESULT Success [Automation Command Executed] (Rule)##

Rule Name: WIFI Update Password RESULT Success
Event Name: Automation Command Executed
Rule Tags:
Custom Constraint List (2):
Execute Rule if: Matches
Automation Command NameEqualsWIFI Update Password RESULT
Command ValueEquals0

##Actions (1):##

AST ExecAMC

Constraint: (none)

CMDname: AST Update Application Subtitle
CMDvalue: Password Changed!
runBG:
delay:

.
.
.
.

:exclamation: The following Rule is optional. It contains Actions that work with my system. You can do whatever you want here, such as including your own Actions, or omit this Rule altogether…

This Rule is fired from the JScript when something goes wrong, with a Command Value of NOT 0.

##WIFI Update Password RESULT Fail [Automation Command Executed] (Rule)##

Rule Name: WIFI Update Password RESULT Fail
Event Name: Automation Command Executed
Rule Tags:
Custom Constraint List (2):
Execute Rule if: Matches
Automation Command NameEqualsWIFI Update Password RESULT
Command ValueNot Equals0

##Actions (1):##

WIFI Ask Question

Constraint: (none)

question: [:CommandValue]
buttons: Ok
description: Check the Log file for more information. (WIFIchange.txt)
AMCname:
BGcolor:
TPcolor:

##DB Tools Import Files

WIFI_Automation_TaskType_Report.zip (2.0 KB)
WIFI_Script.zip (5.1 KB)


##BAT File

This is NOT a DB Tools Import File. It is a BAT file. Save this and extract it to the path where PLINK is located.

WIFIexecBAT.zip (318 Bytes)

##Creating a Private/Public Key Pair

You can use a Key File to login to your Router instead of using a Password. To use this feature, you need to generate a Public/Private Key Pair. This is done using a tool named puttygen,exe which comes with the PuTTY package.

  • run puttygen.exe

  • click Generate and move your mouse around in the blank area of the dialog to create randomness

  • the Public Key is the top part - you will save this key in your Router by copying the text and pasting it into your Router via the Web Admin. You can also save the Public Key to a file and open it later with Notepad to copy and paste it’s content.

  • the Private Key will be saved to a file on your computer when you click Save Private Key


###Generate Key Pair


###Save Public and Private Keys


##Saving Public Key to your Router

The Public Key needs to be registered in your Router.

This is the Public Key.
Paste this single line into “Authorized Keys” as-is… no linefeeds, no tabs.

The Format is:

ssh-rsa KEYREALLYLONGENDINGWITH== comment

Example:

ssh-rsa AAAAAAasdfETRU3253NzaC1yc2EAAAABJQAAAQEAjtSdrYkLp68...== rsa-key-20140702

Different Router Firmware has different locations in the Web Admin for this key. The 2 examples given are for an Asus RT-AC66U with AsusMerlin-WRT firmware (close to stock) and for a Router running DD-WRT firmware.


###Asus RT-AC66U with AsusMerlin-WRT firware (close to stock)

The Public Key goes in Administration > System > SSH Authentication key. You also need to enable SSH and set a Port to be able to use this feature. Telnet will not work.


###DD-WRT Firmware

The Public Key goes in Services > Services > Secure Shell >Authorized Keys. You also need to enable SSH and set a Port to be able to use this feature. Telnet will not work.


When you use PuTTY, you specify your Private Key File in the Session Settings under Connection > SSH > Auth


When you use PLINK, you specify your Private Key File using the -i myrouterkeyfile.ppk parameter …

plink.exe -ssh USER@HOST -P PORT -i myrouterkeyfile.ppk
plink.exe -ssh admin@192.168.0.1 -P 22 -i myrouterkeyfile.ppk
plink.exe -ssh root@192.168.0.1 -P 22 -i myrouterkeyfile.ppk

##Running Commands on your Router using PuTTY

Most Routers use a Linux-type operating system, and you can issue commands to the Router through the shell command line using PuTTY or another Telnet or SSH client program.

The WiFi Password(s) are stored in your Router in variables in an area called NVRAM. We can read these variables, and set (overwrite) them with other values.

To see what is stored in NVRAM, issue the command:

nvram show

That command will output a lot of information that is very hard to sift through …


So to get a shorter list of variables, we can filter it. Most Routers store the WiFi passwords in similar variables such as:

// 2.4 GHz band, NVRAM variable for MAIN Network
wl0_wpa_psk
// 2.4 GHz band, NVRAM variables for Guest Networks 1-3
wl0.1_wpa_psk
wl0.2_wpa_psk
wl0.3_wpa_psk
	
// 5.0 GHz band, NVRAM variable for MAIN Network
wl1_wpa_psk
// 5.0 GHz band, NVRAM variables for Guest Networks 1-3
wl1.1_wpa_psk
wl1.2_wpa_psk
wl1.3_wpa_psk

We can filter the nvram show command to list only the WiFi Network Password variables using grep, and sort them alphabetically, as such:

nvram show | grep wl.*_wpa_psk | sort


If we just want to see all the WiFi Guest Network Password variables, we refine the filter as such:

nvram show | grep wl..._wpa_psk | sort


To set a new Password for a Network, use the the nvram set command …

// set a new Password for 2.4 GHz band Guest Network 1
nvram set wl0.1_wpa_psk=newpassword

After setting any new Passwords, we need to “save” them using the nvram commit command:

nvram commit


And finally, for the changes to take effect, we need to either restart the Wireless Service , or reboot the Router:

// restart wireless service (only available on certain firmware)
service restart_wireless
// reboot router (DD-WRT firmware requires reboot)
reboot

1 Like

#How the Script Works

Now that you know how to run commands on your Router, we can explain how the Script operates to accomplish these tasks in an automated fashion.

In summary:

  • a Rule prompts for a password, and passes that password to the script
  • script accepts the password as a parameter and checks for illegal characters
  • execute a BAT file (multiple times) that invokes PLINK to send a single command to the Router
  • log results of the BAT file and PLINK command
  • update WiFi Task Type
  • invoke an Automation Command Rule for post-processing (optional)

##setPW()##

The main function in the script is setPW() and it is called via the script Handler as such:

// via Execute Script Action
wifi.setPW('newpassword')

// via {CALL:X}
{CALL:wifi.setPW('newpassword')}

That ^ will start the process to change the password, and log results to the Log file (WIFIchange.txt). You will be notified only if there were any problems during the process.


##Parameter variables

Before just trying the above, there some variables at the very top of the script that you need to configure so that it can locate the BAT file and Log file and PLINK, and connect to your Router using the IP, Port, Username, Password, and Private Key File (optional):

// minimum length for WiFi Network Password
var minPWlength = 8;

// BAT file settings, the BAT file and PLINK should be in the same Path
var batDrive = 'D:';
var batPath  = "D:/Programs/POS/router/";
var batFile  = "WIFIchange.bat"; // complex BAT (NOT preferred, override below)
	batFile  = 'WIFIexec.bat';   // simple BAT (preferred)
var batLog   = "WIFIchange.txt";
var batRes   = "WIFIresult.txt";
var batHidden = true;

// ROUTER settings
var rHost = '192.168.1.1';
var rPort = '22';

// these settings are arbitrary, but are used as part of the Task Name and Identifier
var rName = 'RouterJV';
var rType = 'Trendnet TEW812DRU';

// router firmware dictates which commands to issue in the BAT file
var rFirmware = 'DD-WRT'; // reboot the router
var rFirmware = 'AsusMerlin-WRT'; // restart wireless service

// generally, the username via SSH for DD-WRT firmware is 'root', while other firmware uses 'admin'
var rUser = rFirmware=='DD-WRT' ? 'root' : 'admin';

// we can use a Password or Keyfile to login to the Router
var rPass = 'myrouterpassword';
var rKey  = 'keyprivjv.ppk';

##execRouter()##

The secondary function is execRouter() which is the real workhorse responsible for doing all of the dirty work of running commands on your Router using a simple BAT file and PLINK.

The way it is currently configured, it will set all Guest Network Passwords to the same value. If you want something different, then you need to modify the script to suit your needs.

	// 2.4 GHz band, passwords for networks 1-3
	var pw24_1=pw;
	var pw24_2=pw;
	var pw24_3=pw;
	
	// 5.0 GHz band, passwords for networks 1-3
	var pw50_1=pw;
	var pw50_2=pw;
	var pw50_3=pw;

The other thing the script is configured to do by default is to only set the Passwords for Network 1 on both the 2.4 GHz and 5.0 GHz band, while leaving the Passwords for Guest Networks 2 and 3 unchanged: Again, if you want different functionality, you will need to modify the script.

	batSteps.push("Current Passwords");
	batParms.push(commonParms +" "+'"'+cShowNets+'"');
	
	batSteps.push("Setting Password "+rGUEST24net1+"="+pw24_1);
	batParms.push(commonParms +" "+'"'+cSetNet24_1+'"');
	
	batSteps.push("Setting Password "+rGUEST50net1+"="+pw50_1);
	batParms.push(commonParms +" "+'"'+cSetNet50_1+'"');
	
	batSteps.push("Commit");
	batParms.push(commonParms +" "+'"'+cCommitNVRAM+'"');
	
	batSteps.push("New Passwords");
	batParms.push(commonParms +" "+'"'+cShowNets+'"');
	
	batSteps.push("Restarting ("+(rFirmware=='DD-WRT' ? cREBOOT : cRESTARTwifi)+")");
	batParms.push(commonParms +" "+'"'+(rFirmware=='DD-WRT' ? cREBOOT : cRESTARTwifi)+'"');

Looking closer at the above push() methods, we can see we are running 6 commands on the Router, in sequence:

cShowNets
cSetNet24_1
cSetNet50_1
cCommitNVRAM
cShowNets
cREBOOT 

If we look just a little earlier in the script, we can see what those commands actually are:

###cShowNets

Lists current Guest Network WiFi Passwords:

var cShowNets = "nvram show | grep wl..._wpa_psk | sort | sed 's/wl/\\r\\nwl/g'";

nvram show | grep wl..._wpa_psk | sort | sed 's/wl/\\r\\nwl/g'

###cSetNet24_1

Sets the Password for the 2.4 GHz Guest Network 1:

var cSetNet24_1 = "nvram set "+rGUEST24net1+"="+pw24_1;

nvram set wl0.1_wpa_psk=newpassword

###cSetNet50_1

Sets the Password for the 5.0 GHz Guest Network 1:

var cSetNet50_1 = "nvram set "+rGUEST50net1+"="+pw50_1;

nvram set wl1.1_wpa_psk=newpassword

###cCommitNVRAM

Saves changes to NVRAM.

var cCommitNVRAM = "nvram commit";

nvram commit

###cShowNets

Lists current Guest Network WiFi Passwords (again):

var cShowNets = "nvram show | grep wl..._wpa_psk | sort | sed 's/wl/\\r\\nwl/g'";

nvram show | grep wl..._wpa_psk | sort | sed 's/wl/\\r\\nwl/g'

###cREBOOT

Reboots the Router.

var cREBOOT = "reboot";

reboot

So the script will run each of those commands in sequence by executing the BAT file, which invokes PLINK to issue the command and leave a result in the file WIFIresult.txt.

var batResult = file.Starter(batPath+batFile).With(batParms[p]).WorkOn(batPath).Hidden.ShellExecute();

After each command, we read the content of the Result File (WIFIresult.txt) to check for information or errors, and use that info for logging in the Log File (WIFIchange.txt):

var opres = file.ReadFromFile(batPath+batRes);

var filewrite = file.AppendToFile(batPath+batLog,batSteps[p]+" ----------\r\n");
var filewrite = file.AppendToFile(batPath+batLog,lines+"\r\n\r\n");

Finally, if all commands are executed with Success, we update the Task Types by marking the old Task as Complete, and Add a new Task containing the Password Change information:

var wifi = gqlEXEC(updateTaskByIdentifier([taskType], [cident], isCompleted));

var wifi = gqlEXEC(addTasks([taskType],[taskName],isCompleted,customData,userName));

The last step is to execute an Automation Command for SUCCESS which triggers Optional Rule #1 (WIFI Update Password RESULT Success) with a Command Value of 0 to fire any other Actions:

	// execute Automation Command for any post-process Actions
	cmd.Execute('WIFI Update Password RESULT:0');

Or if there was a problem anywhere along the way, we use the throwError() function in to gather information and call Optional Rule #2 (WIFI Update Password RESULT Fail), feeding the error information in as the Command Value:

	// execute Automation Command for any post-process Actions
	cmd.Execute("WIFI Update Password RESULT:"+errmsg);

That’s about all.

… reserved for updates …

… reserved for updates …

Think your missing the point, he specifically wants to change the password routinely and show in samba automatically.

Thanks for sharing this information. It’s useful.

Tell me, this script may working with mikrotik routers with CAPsMAN? Or with Unifi networks?

Dont know about changing password but unifi gateway controller has an api you could look at using their hotspot options and samba to create a login.
Could be as basic as a code on receipt they enter and unifi queries samba to auth the code