Skip to end of metadata
Go to start of metadata

文章来源于宏时数据zabbix培训师、由宏时数据运营的#Zabbix开源社区#签约专家米宏@小米飞猫,收录于宏时数据知识库 #Zabbix运维经验模块。


按字母顺序排序行:

var data='beta\nalpha\ndelta';
var array=data.match(/.*/gm);
return array.sort().join("\n");

删除注释并按字母顺序排序:

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;

统计行数:

return value.split(/\r\n|\r|\n/).length;

需要监察的具体服务:

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);

对浮点数数组从大到小排序:

return value.match(/[0-9\.]+/gm).sort(function(a, b){return a - b}).reverse();

除余:

return value % 180

模式匹配:

var temp = "Wel to come to W3Docs to asd";
return (temp.match(/to/g) || []).length;

验证和提取:

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);
}

删除行首空白符:

.replace(/^\s+/gm,'');

删除行首,行尾空白符:

.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;

提取所有数字:

return "This 13 this is another number 54 and third number 222".match(/\d+/g);

使用正则判断是否为空值:

return value.match(/.*/) ? value : 0;

检测字符串是否有值:

if (value.search("kaste") > 0) {
return value;
}
else {
return 0
}

提取第一组:

var regexp = /<ServiceName xsi:type="xsd:string">([\w\s]+)<\/ServiceName>/gm;
var match = regexp.exec(value);
return match.length;

转义特殊字符:

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);

发现ODBC后删除LLD宏:

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');

整型数组排序:

return value.sort(function(a, b){return a - b});

数字排序:

return value.match(/[0-9]+/gm).sort(function(a, b){return a - b});

删除空行:

return value.trim().replace(/^\s*[\r\n]/gm, '');

统计行:

return value.split(/\r\n|\r|\n/).length;

从文本中打印端口。


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(',');

传输SNMP发现:JSONPath:

$.[*].["{#SNMPINDEX}"]

预处理转换SNMPINDEX,移除右边的所有内容:

// 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);

目录的大小:


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));

对文本 '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,",");

通过二元:

return value.match(/sbin.zabbix_agentd.conf$/gm) ? 1 : 0;

删除所有新行字符:

return value.replace(/(\r\n|\n|\r)/gm,"")

删除所有空间:

return value.replace(/(\s)/gm,"")

删除所有双引号:

return value.replace(/(\")/gm,"")

在行开头插入:

return value.replace(/^/,"{\"data\":[{\"{#LANG}\":\"")

在行尾插入:

return value.replace(/$/,"\"}]}")

删除末尾的最后一个字符:

return value.replace(/.$/,"")
return value.match(/^.*bash$/gm).join("\n");

逗号替换成换行符:

return value.replace(/,/gm,"\n")

移除重复的数据:

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(/$/,"\"}]}")

搜索链接:

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")

格式化 /etc/passwd 生成LLD 的 discovery:

return value.match(/^.*bash$/gm).join("\n").replace(/..bin.bash$/gm,"\"},").replace(/:.*:/gm,"\",\"{#PATH}\":\"").replace(/^/gm,"{\"{#USER}\":\"").replace(/^/,"{\"data\":[").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);

整个数字转换成小写:

return JSON.parse(JSON.stringify(value, function(a, b) { return typeof b === "string" ? b.toLowerCase() : b }));

16进制 to ASCII(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}']

替换 bash的变量:

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);
}
  • No labels