JavaScript Zabbix preprocessing cheat sheet, substitution samples

remove duplicate text values:

function uniq(a) {
    return a.sort().filter(function(item, pos, ary) {
        return !pos || item != ary[pos - 1];
    });
}
return uniq(JSON.parse(value));
Remove duplicates:
// remove duplicates
var lookup = {};
var items = JSON.parse(value);
var result = [];

for (var item, i = 0; item = items[i++];) {
  var url = item.url;

  if (!(url in lookup)) {
    var row = {};
    lookup[url] = 1;
    row["url"] = item.url;
    row["price"] = item.price;
    row["District"] = item.District;
    row["City"] = item.City;
    row["Street"] = item.Street;
    row["Rooms"] = item.Rooms;
    row["Area"] = item.Area;
    row["Floor"] = item.Floor;
    row["Series"] = item.Series;
    row["Type"] = item.Type;
    row["Facilities"] = item.Facilities;
    result.push(row);
  }
}
return JSON.stringify(result);
match real ip addresses in the hosts file:
return value
.match(/^[^#]+/gm)
.sort().join("\n")
.match(/^[1-9]+.*$/gm)
.sort().join("\n")
.trim()
.replace(/^\s*[\r\n]/gm, '');
work with run extra scenario of a keyword is found
// look for keyword "pod" (including double quotes)
if (value.search("\"pod\"") > 0) {
// if pod has been found then execute extra JSONPath to find name

// Set the plain text to be a JSON object
var jsonData = JSON.parse(value);

// Count length of array. How many pods has been failed
lenghtOfArray=jsonData.length;

// Define an array to put inside all failed pods
var answerArray = [];

// Locate each pod and put inside answer Array
for(var pod = 0; pod < lenghtOfArray; pod++){
answerArray.push(jsonData[pod].metric.pod);
}

// Return all failed pods, and convert array to text with a comma as dividor
return answerArray.join(", ");

}
else {
// If "pod" was not found, then nothing happens
return 0
}
Sort lines alphabetically:
var data='beta\nalpha\ndelta';
var array=data.match(/.*/gm);
return array.sort().join("\n");
Remove comments and sort alphabetically:
return value
.match(/^[^#]+/gm)
.sort().join("\n")
.trim()
.replace(/^\s*[\r\n]/gm, '')
.match(/.*/gm).sort()
.join("\n")
.replace(/^\s*[\r\n]/gm, '');
lld:
var lld = [];

// this line is important to match all required patterns right away. Otherwise the upcoming code will fail.
var lines = value.match(/^.*:\d+.*\"[^\"]+\".*$/gm);

// go through all lines which match critera
var lines_num = lines.length;
for (i = 0; i < lines_num; i++)
{
  var row = {};
  row["port"] = lines[i].toString().match(/:([0-9]+)/)[1];
  row["process"] = lines[i].toString().match(/\"([^\"]+)\"/)[1];
  lld.push(row);
}
  return JSON.stringify(lld);
  
var arr1 = [ 1, 2, 3, 5 ];
var arr2 = [ 1, 4, 5, 6 ];
// merge, remove dublicates, sort
var arr3 = arr1.concat(arr2)
.reduce(function(a,b){if(a.indexOf(b) < 0)a.push(b);return a;},[])
.sort(function(a, b){return a - b});
return arr3;
Count of lines:
return value.split(/\r\n|\r|\n/).length;
Specific services to monitor:
var lines = '{$SERVICES_TO_MONITOR}'.split("|");
var lld = [];
var lines_num = lines.length;
for (i = 0; i < lines_num; i++)
{  
   var row = {};  
   row["{#NAME}"] = lines[i]  
   lld.push(row);
} 
return JSON.stringify(lld);
Define:
service1|service2
Sort a floating number array from biggest to smalles:
return value.match(/[0-9\.]+/gm).sort(function(a, b){return a - b}).reverse();
value mod 180:
return value % 180
Occurence of pattern:
var temp = "Wel to come to W3Docs to asd";
return (temp.match(/to/g) || []).length;
Validate and extract:
var lld = [];

if (value.match(/1 packets transmitted, 1 received/)) {
var lines = value
.match(/^.*1 packets transmitted, 1 received/gm)
.join("\n")
.replace(/^PING /gm,"")
.match(/^[0-9\.]+/gm);

var lines_num = lines.length;
for (i = 0; i < lines_num; i++)
{
  var row = {};
  row["{#IP.POS}"] = lines[i]
  lld.push(row);
}
return JSON.stringify(lld);
}
else
{
return JSON.stringify(lld);
}
Remove leading spaces:
.replace(/^\s+/gm,'');
Remove leading and trailing spaces:
.replace(/^\s+|\s+$/gm,'')
var string="kaste ta 13 da suns 66 iet"
var re=/\d+/g;
return string.match(re) ? re.exec(string) : 0;
Extract all numbers:
return "This 13 this is another number 54 and third number 222".match(/\d+/g);
Detect if value is there with regex
return value.match(/.*/) ? value : 0;
Detect if value is there with strings
if (value.search("kaste") > 0) {
return value;
}
else {
return 0
}
Extract first group:
var regexp = /<ServiceName xsi:type="xsd:string">([\w\s]+)<\/ServiceName>/gm;
var match = regexp.exec(value);
return match.length;
Escape special characters:
var jsonData = JSON.parse(value);

lenghtOfArray=jsonData.length;
for(var row = 0; row < lenghtOfArray; row++){
jsonData[row].Pattern = jsonData[row].Pattern
.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

return JSON.stringify(jsonData);
Remove LLD macro after ODBC discovery:
return value
.replace(/{#ID}/gm,'ID')
.replace(/{#NAME}/gm,'NAME')
.replace(/{#VALUE}/gm,'VALUE')
.replace(/{#CREATED_ON}/gm,'CREATED_ON')
.replace(/{#UPDATED_ON}/gm,'UPDATED_ON')
.replace(/{#ISDELETED}/gm,'ISDELETED');
Sort and integer arrar:
return value.sort(function(a, b){return a - b});
Sort numbers:
return value.match(/[0-9]+/gm).sort(function(a, b){return a - b});
Remove empy lines:
return value.trim().replace(/^\s*[\r\n]/gm, '');
Count lines:
return value.split(/\r\n|\r|\n/).length;
Print new ports from context:

var rownput_1 = [
        { "value": "22,3306,5432,10051" },
        { "value": "22,3000,3306,5432,10051" },
        { "value": "22,3306,5432,10051" },
        { "value": "22,3306,5432,10051" }
];
var rownput_2 = [
        { "value": "22,3306,5432,10051" },
        { "value": "22,3000,3306,5432,10051" },
        { "value": "22,3306,5432,10051" },
        { "value": "22,3306,5432,10050,10051" }
];

var array = JSON.parse(value);

var occurances = {};

// start two loops
// first loop starts. it will go through array elements (AKA rows)
var arraySize=array.length;
for (var row = 0; row < arraySize; row++) {
	
	// start working with one specific line in array
    var cur = array[row];
    // count how many ports are in the line
    var countOfPorts=cur["value"].split(",").length;
    
    // start a loop to go through all ports
    for (var port = 0; port < countOfPorts; port++) {
		// select one specific port. put it in 'cur_num' variable
        var cur_num = cur["value"].split(",")[port];
        // if the corresponding number does not have any value yet (for example when analyzing first line)
        occurances[cur_num] = (occurances[cur_num] == null ? 1 : occurances[cur_num] + 1);
    }
}

// Find the maximum value (the amount of occurances that non-odd one outs have)
var max = 0;
for (var key in occurances) {
    if (max < occurances[key]) {
        max = occurances[key];
    }
}
var result = []; // Find all of the odd ones out
for (var key in occurances) {
    if (occurances[key] != max) {
        result.push(key);
    }
}
return result.join(',');
Transfor SNMP discovery: JSONPath:
$.[*].["{#SNMPINDEX}"]
Preprocessing to transform SNMPINDEX, erase everything to the right:
// put the output from JSONPath result as an array of elements
var obj = JSON.parse(value);

// count the elements in input
var lines_num = obj.length;

// define new array
var lld = [];

// transform each element in array and put in new array
// .replace(/\..*$/gm,"") means we will erase any other character starting from first dot (.)
for (i = 0; i < lines_num; i++)
{
  var row = {};
  row["{#SNMPINDEX}"] = obj[i].replace(/\..*$/gm,"");
  lld.push(row);
}
return JSON.stringify(lld);
Dirs and sizes:


var jsonData = JSON.parse(value);

// check each row and remove the data
for(var row = 0; row < jsonData.length - 1; row++){
	// this will check the first condition.
  var pointer = 1;
  while(row + pointer < jsonData.length && jsonData[row].SIZE == jsonData[row + pointer].SIZE){
  	if( jsonData[row].DIR.startsWith(jsonData[row+1].DIR) ){
    	jsonData.splice(row + pointer, 1);
    }
    else	{
    	pointer++;
    }
  }
	
  // this will check the second condition.
  // for the second condition, it needs extra loop while the difference of size is smaller than 20480.
  pointer = 1;
  while(row + pointer < jsonData.length && jsonData[row].SIZE - jsonData[row + pointer].SIZE < 20480){
    if (jsonData[row + pointer].DIR.startsWith(jsonData[row].DIR)) { 
      // remove the current row and then reduce row because array items after row will be shifted
      jsonData.splice(row, 1);
      row--;
      break;
    }
    pointer ++;
  }
}

return JSON.stringify(jsonData.slice(0,10));
Summ all integers inside text '111+222+333':
var separeted = value.split("+");
var sum = 0;
for (var i = 0; i < separeted.length; i++) {
sum += parseInt(separeted[i].toString().match(/(\d+)/));
}
return sum;
$.body.data.result
var obj = JSON.parse(value);
return obj.length;
1:
return "SIZE,FILE\n"+value.replace(/\t/gm,",");
Check a pattern in one input:
return value.match(/sbin.zabbix_agentd.conf$/gm) ? 1 : 0;
Remove all new line characters:
return value.replace(/(\r\n|\n|\r)/gm,"")
Remove all spaces:
return value.replace(/(\s)/gm,"")
Delete all double quotes:
return value.replace(/(\")/gm,"")
Insert at the start of line:
return value.replace(/^/,"{\"data\":[{\"{#LANG}\":\"")
Insert at the end of line:
return value.replace(/$/,"\"}]}")
Delete last character at the end:
return value.replace(/.$/,"")
return value.match(/^.*bash$/gm).join("\n");
Deform array
return value.replace(/,/gm,"\n")
Remove duplicates:
return value.reduce(function(a,b){if(a.indexOf(b) < 0)a.push(b);return a;},[]);
Create a discovery rule from content en,fr,lv. Solution:
return value.replace(/,/g,"\"},{\"{#LANG}\":\"").replace(/^/,"{\"data\":[{\"{#LANG}\":\"").replace(/$/,"\"}]}")
Search for links:
return value.match(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.\/_?&=]+/gm).reduce(function(a,b){if(a.indexOf(b)< 0)a.push(b);return a;},[]).join("\n")
Format /etc/passwd for discovery:
return value.match(/^.*bash$/gm).join("\n").replace(/..bin.bash$/gm,"\"},").replace(/:.*:/gm,"\",\"{#PATH}\":\"").replace(/^/gm,"{\"{#USER}\":\"").replace(/^/,"{\"data\":[").replace(/.$/,"]}")
Replace:
https:\/\/catonrug.blogspot.com\/2020\/01\/find-files-in-specific-date-time-between.html
With:
https://catonrug.blogspot.com/2020/01/find-files-in-specific-date-time-between.html
return value.replace(/https?:\\\/\\\/([a-z\.]+)\\\/([0-9]+)\\\/([0-9]+)\\\//gm, "https:\/\/$1\/$2\/$3\/");
var lld = [];
var lines = value.match(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.\/_?&=]+/gm).reduce(function(a,b){if(a.indexOf(b)< 0)a.push(b);return a;},[]);
var lines_num = lines.length;
for (i = 0; i < lines_num; i++)
{
  var row = {};
  row["{#URL}"] = lines[i]
  lld.push(row);
}
return JSON.stringify(lld);
Lowercase whole array:
return JSON.parse(JSON.stringify(value, function(a, b) { return typeof b === "string" ? b.toLowerCase() : b }));
HEX to ASCII:
var out = "";
for (var i = 0, nums = value.split(" "); i < nums.length; i++) {
     out += String.fromCharCode(parseInt(nums[i], 16));
} 
return out;
locate TOTAL_MB where TABLESPACE = {#TABLESPACE}
var obj = JSON.parse(value),
 result = obj.filter(function(e) {
 return e['{#' + 'TABLESPACE}'] == '{#TABLESPACE}';
 });
return result[0]['{#' + 'TOTAL_MB}']
Replace bash variables:
var lld = [];

// check if there are any links at all
if (value.match(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.\/\$_?&=]+/gm)) {

	// if there are links, then extract and make sure there are no dublicates:
	var lines = value.match(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.\/\$_?&=]+/gm).reduce(function(a,b){if(a.indexOf(b)< 0)a.push(b);return a;},[]);
	var lines_num = lines.length;
	
	for (i = 0; i < lines_num; i++)	{
		
		var row = {};

		// a patch to extract a variable (the one with a dollar sign) 
		// if the following input turn out some sort of bash code
		if (lines[i].match(/\$[a-z]+/gm)) {
		  
			// extract full title of variable and value
			var variable = value.match(/([a-z]+)=([a-z0-9\.]+)/gm);

			// how many variables are in bash code
			var count_of_variables = variable.length;
			
			// go through all variables in bash code
			for (j = 0; j < count_of_variables; j++) {
				var regexp = /([a-z]+)=([a-z0-9\.]+)/gm;
				var unpack = regexp.exec(variable[j]);

				var var_name = '$' + unpack[1];
				var var_value = unpack[2];
				
				// do replacement for the link
				for (k = 0; k < (lines[i].match(/\$/g) || []).length; k++) {
					lines[i] = lines[i].replace(var_name,var_value);
				}
				
			}

			row["{#POST.URL}"] = lines[i];
		  
		} else {
			row["{#POST.URL}"] = lines[i];
		}

		lld.push(row);
	}
	
	return JSON.stringify(lld);

} else {
	return JSON.stringify(lld);
}

1 comment:

  1. AnonymousMay 01, 2023

    // put the output from JSONPath result as an array of elements
    var obj = JSON.parse(value);

    // count the elements in input
    var lines_num = obj.length;

    // define new array
    var lld = [];

    // transform each element in array and put in new array
    // .replace(/\..*$/gm,"") means we will erase any other character starting from first dot (.)
    for (i = 0; i < lines_num; i++)
    {
    var row = {};
    row["{#SNMPINDEX}"] = obj[i].replace(/\..*$/gm,"");
    lld.push(row);
    }
    return JSON.stringify(lld);

    Error TypeError: undefined not callable (property 'replace' of [object Object])

    Could you Please check the script for zabbix 6.4.2. Thanks in advanced

    ReplyDelete