<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Делимся скриптами]]></title><description><![CDATA[<p dir="auto">Вообще не хватает подобного топика, все полезные скрипты или пользовательские функции разбросаны по форуму или чату в телеграмм, предлагаю публиковать и собирать всё в одной теме.</p>
<p dir="auto">В Script Library можно добавить скрипты (либо они будут уже созданы при свежей уставноке):</p>
<pre><code>Hook::StatusPoll
Hook::ConfigurationPoll
Hook::TopologyPoll
Hook::AcceptNewNode
Hook::CreateInterface
Hook::CreateSubnet
Hook::UpdateInterface
Hook::EventProcessor
Hook::InstancePoll
Hook::PostObjectCreate
Hook::DiscoveryPoll
Hook::AlarmStateChange
Hook::UnboundTunnelOpened
Hook::BoundTunnelOpened
</code></pre>
<p dir="auto"><strong>Hook Scripts:</strong></p>
<p dir="auto"><strong>Hook::CreateInterface:</strong></p>
<pre><code>if ($1-&gt;name imatch "802.1Q Encapsulation Tag *|Management port|Aux*|Console*|InLoopBack0|MEeth0*|null0*|meth0*|enet0*|oob|M-Ethernet")
	{
		return false
	}

if (($node-&gt;sysDescription ~= "^Linux ") &amp;&amp;
	(($1-&gt;ifType == "1" ||
	  $1-&gt;ifType == "22" ||
	  $1-&gt;ifType == "24" ||
	  $1-&gt;ifType == "124"))
	)
	{
		return false;
	}
return true;
</code></pre>
<p dir="auto">###########======---</p>
<pre><code>if ($node-&gt;driver == "CISCO-SB"){
  snmp = CreateSNMPTransport($node);
  state = SNMPGetValue(snmp, ".1.3.6.1.2.1.2.2.1.8." . $1-&gt;ifIndex);
  if (state == 6)
    return false;
}
return true;
</code></pre>
<p dir="auto">###########======---</p>
<pre><code>if ($1-&gt;name ~= "(?i).*Teredo.*|.*isatap.*|.*Bluetooth.*|sit0")
   return false;
snmp = CreateSNMPTransport($node);
state = SNMPGetValue(snmp, ".1.3.6.1.2.1.2.2.1.8." . $1-&gt;index);
if (state == 5)
   return false;

return true;
</code></pre>
<p dir="auto">###########======---</p>
<p dir="auto">Если логическое утверждение истинно, вы получаете первую часть, а если оно ложно, вы получаете вторую.</p>
<pre><code>sysDescription = ($node-&gt;sysDescription == "") ? $node-&gt;readAgentParameter("System.Uname") : $node-&gt;sysDescription;
if (sysDescription ~= "^Linux [A-z]+[0-9]+.")
</code></pre>
<p dir="auto"><strong>Hook::AcceptNewNode:</strong></p>
<p dir="auto">Can be used as additional filter for network discovery to avoid unnecessary communications.<br />
Этот хук срабатывает только на добавление новых нод - если нода уже добавлена то с ней ничего не случится.<br />
Более того, он не срабатывает при ручном добавлении - это только дополнительный фильтр для discovery.</p>
<pre><code>// macs = %(01:E8:EE:94:91:C8, 01:E8:EE:91:DD:21, 01:E8:EE:92:71:FD, 01:E8:EE:93:72:F9, 01:E8:EE:92:66:DD, 01:E8:EE:94:91:7E, 01:E8:EE:9C:32:D4);

node1 = "01:E8:EE:94:91:C8";
node2 = "01:E8:EE:91:DD:21";
node3 = "01:E8:EE:92:71:FD";


if (AddrInSubnet($ipAddr, "10.10.0.0", "255.254.0.0")
|| AddrInSubnet($ipAddr, "10.20.0.0", "255.255.254.0"))
	return true;

return false;

return not ($macAddr in %(node1, node2, node3));
</code></pre>
<p dir="auto">P.S. здесь дополнительно ещё проверка по MAC.</p>
<p dir="auto">Конвертивание эпохи Unix в человекопонятную дату(human readable date)</p>
<pre><code>return strftime("%d.%m.%Y %H:%M:%S", $1);
</code></pre>
<p dir="auto">###########======---</p>
<p dir="auto">Скрипт для HP ILO на примере instance discovery <code>.1.3.6.1.4.1.232.3.2.3.1.1.4.0.{instance} и Log Drive status {instance} {instance-name}</code> для подмены значений в более информативный вид</p>
<pre><code>switch ($1)
{
	case 2:
		return "ok";
		break;
	case 3:
		return "failed";
		break;
	case 4:
		return "unconfigured";
		break;
	case 5:
		return "recovering";
		break;
	case 6:
		return "readyForRebuild";
		break;
	case 7:
		return "rebuilding";
		break;
	case 8:
		return "wrongDevice";
		break;
	case 9:
		return "badConnect";
		break;
	case 10:
		return "overheating";
		break;
	case 11:
		return "shutdown";
		break;
	case 12:
		return "expanding";
		break;
	case 13:
		return "notAvailable";
		break;
	case 14:
		return "queuedForExpansion";
		break;
	case 15:
		return "multipathAccessDegraded";
		break;
	case 16:
		return "earsing";
		break;
	default:
		return "other";
		break;
}
</code></pre>
<p dir="auto"><strong>Instance discovery script's:</strong></p>
<p dir="auto"><strong>Для Net.Interface.BytesIn({instance})</strong>, благодаря которому на выходе в графиках получаем DCI по нужным нам интерфейсам, в данном случае eth|bond для Linux сервера.</p>
<pre><code>name=substr($1,rindex($1, " ")+1);
if (name ~= "eth|bond")
{
return %(true, name);
}
return false;
</code></pre>
<p dir="auto"><strong>Для снятия ошибок с Linux интерфейсов.</strong></p>
<pre><code>ExternalParameterShellExec = Interface.errors(*):ethtool -S $1 | grep $2 | awk '{print $$2}'
</code></pre>
<p dir="auto">В библиотеке скриптов создаём скрипт ethtool_errors_instance:</p>
<pre><code>ifaces = AgentReadList($node, "Net.InterfaceNames");
instances = %();
c = 0;
for(i : ifaces)
{
	if (i ~= "eth|em|p55p|p1p|eno|ens|enp") {

	   instances[c++] = i . ",rx_crc_errors";
   	   instances[c++] = i . ",rx_missed_errors";
	   instances[c++] = i . ",rx_no_buffer_count";
	}
}
return instances;
</code></pre>
<p dir="auto">Создаём DCI Interface.errors({instance}), в Instance discovery method ставим Script и указываем имя созданного скрипта, ethtool_errors_instance.</p>
<p dir="auto"><strong>Общее:</strong></p>
<p dir="auto">Скрипт с рекурсивной функцией и поиском по нужным\необходимым параметрам, в данном случае по snmp sysDescription коммутатора</p>
<pre><code>sub GetTree (nodeID)
{
Tree = FindObject(nodeID);
children = GetObjectChildren(Tree);

foreach (n : children)
 {
	//println ("Name: " . n-&gt;name);
	if (n-&gt;name != null &amp;&amp; classof(n) == "Node")
	{
		if (n-&gt;sysDescription ~= "^D-Link DES-3028" &amp;&amp; n-&gt;comments == "")
	{
		println ("Name: " . n-&gt;name . ", sysDescription: " . n-&gt;sysDescription . ", IP: " . n-&gt;ipAddr);
	}
}
GetTree(n-&gt;id);
  }
}

GetTree(2);
</code></pre>
<p dir="auto">Примерно аналогичный скрипт, но выведет custom атрибуты по интерфейсам, все кроме .dlink.slotSize и uptime</p>
<pre><code>sub GetTree (nodeID)
{
Tree = FindObject(nodeID);
children = GetObjectChildren(Tree);

foreach (i : children)
 {
	{
		attributes = i-&gt;customAttributes;
		foreach(a : attributes-&gt;keys)
	{
	{
		if ((a != ".dlink.slotSize") &amp;&amp;  (a != "uptime"))
	{
		println (a . " = " . attributes[a] . "," . " Port: " . i-&gt;port . "," . " Interface name: " . i-&gt;name . "," . " Node name: " . Tree-&gt;name);
	}
  }
 }
}

GetTree(i-&gt;id);
  }
}

GetTree(2);
</code></pre>
<p dir="auto"><strong>EPP:</strong></p>
<p dir="auto">Скрипт для и фильтрации по интерфейсам, например для SYS_IF_UP.</p>
<pre><code>ignoreInterfaceRegEx = "^ppp([0-9]+)|802.1Q";

if ($2 ~= ignoreInterfaceRegEx)
  return false;

return true;
</code></pre>
]]></description><link>https://forum.netxms.org/topic/4586/делимся-скриптами</link><generator>RSS for Node</generator><lastBuildDate>Fri, 13 Nov 2026 08:25:00 GMT</lastBuildDate><atom:link href="https://forum.netxms.org/topic/4586.rss" rel="self" type="application/rss+xml"/><pubDate>Fri, 08 Jul 2016 13:53:56 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Делимся скриптами on Mon, 12 Nov 2018 05:50:22 GMT]]></title><description><![CDATA[<p dir="auto"><strong>Cкрипт для перезагрузки свичей Edge-Core по SNMP.</strong></p>
<pre><code>print "Trying reboot switch -&gt; ".$node-&gt;name;
println "  snmpObjectId-&gt;".$node-&gt;snmpOID."  ".$node-&gt;sysDescription;
switch($node-&gt;snmpOID)
{
 case ".1.3.6.1.4.1.259.6.10.94":
  print "ES3528M";
  oid = "1.3.6.1.4.1.259.6.10.94.1.7.3.0";
 break;
 case ".1.3.6.1.4.1.259.10.1.27.101":
  print "ECS3510-28T";
  oid = "1.3.6.1.4.1.259.10.1.27.1.7.3.0";
 break;
/* case ".1.3.6.1.4.1.259.8.1.5":
  println "ES3510";
  oid = "";
 break; */
 case ".1.3.6.1.4.1.259.10.1.27.102":
  print "ECS3510-52T";
  oid = "1.3.6.1.4.1.259.10.1.27.1.7.3.0";
 break;
 case ".1.3.6.1.4.1.259.8.1.11.101":
  print "ES3510MA";
  oid = "1.3.6.1.4.1.259.8.1.11.1.7.3.0";
 break;
 default:
 println "Unknown switch model!";
  return 1;
}println " &gt; ResetOID=".oid;

snmpTransport = CreateSNMPTransport($node);
if ( snmpTransport == null ) return "Unable to connect";
returnValue = SNMPSet(snmpTransport,oid,"3","INTEGER");
if ( returnValue == null ) return "No response. Something went wrong.";
if ( returnValue == 0 ) return "Unable to initiate reload. No SNMP Write Access?";
if ( returnValue == 1 ) return "Reload triggered.";
</code></pre>
<p dir="auto">Скрипт необходимо разместить в "Script Library" например с названием reboot_switch.<br />
Затем в "Object Tools" создать новый инструмент, например "Reboot switch Edge-Core"<br />
В поле "Script" указать "reboot_switch".<br />
Установить "птичку" на "Command generates output".<br />
Не помешает птичка в поле "Confirmation" с соответствующим вопросом (необязательно, но желательно).</p>
]]></description><link>https://forum.netxms.org/post/24998</link><guid isPermaLink="true">https://forum.netxms.org/post/24998</guid><dc:creator><![CDATA[askat]]></dc:creator><pubDate>Mon, 12 Nov 2018 05:50:22 GMT</pubDate></item><item><title><![CDATA[Reply to Делимся скриптами on Fri, 02 Jun 2017 17:13:19 GMT]]></title><description><![CDATA[<p dir="auto">Дамп потоков для Linux.</p>
<pre><code>#!/bin/sh
exec='netxmsd'
if [ "x$1" != "x" ]; then
	exec="$1"
fi
pid=`ps -ax | grep netxmsd | grep -v grep | grep -v capture_netxmsd_threads | awk '{ print $1; }'`
ts=`date +%Y%m%d-%H%M%S`
cmdfile="/tmp/capture_netxmsd_threads.gdb"
echo "set height 0" &gt; $cmdfile
echo "set logging file /tmp/netxmsd-threads.$pid.$ts" &gt;&gt; $cmdfile
echo "set logging on" &gt;&gt; $cmdfile
echo "attach $pid" &gt;&gt; $cmdfile
echo "thread apply all bt" &gt;&gt; $cmdfile
echo "detach" &gt;&gt; $cmdfile
echo "quit" &gt;&gt; $cmdfile
gdb --batch-silent --command=$cmdfile "$exec"
rm $cmdfile
</code></pre>
]]></description><link>https://forum.netxms.org/post/22456</link><guid isPermaLink="true">https://forum.netxms.org/post/22456</guid><dc:creator><![CDATA[hsvt]]></dc:creator><pubDate>Fri, 02 Jun 2017 17:13:19 GMT</pubDate></item><item><title><![CDATA[Reply to Делимся скриптами on Fri, 08 Jul 2016 14:00:37 GMT]]></title><description><![CDATA[<p dir="auto">Модуль debug (в нужном скрипте "use debug;", потом можно использовать "dbgPrintTable(table)"):</p>
<pre><code>sub dbgPaddingLeft(s, len) {
	if (s == NULL) {
		s = "";
	}
	padding = "";
	for (i = 0; i &lt; len - length(s); i++) {
		padding .= " ";
	}
	return padding . s;
}

sub dbgPaddingRight(s, len) {
	if (s == NULL) {
		s = "";
	}
	padding = "";
	for (i = 0; i &lt; len - length(s); i++) {
		padding .= " ";
	}
	return s . padding;
}

sub dbgPrintTable(t) {
	if (t == NULL) {
		return;
	}

	array columnLen;

	for (i = 0; i &lt; t-&gt;columnCount; i++) {
		columnLen[i] = length(t-&gt;columns[i]-&gt;displayName);
	}
	for (i = 0; i &lt; t-&gt;rowCount; i++) {
		for (j = 0; j &lt; t-&gt;columnCount; j++) {
			val = t-&gt;get(i, j);
			if (val == NULL) {
				val = "";
			}
			columnLen[j] = max(columnLen[j], length(val));
		}
	}
	for (i = 0; i &lt; t-&gt;columnCount; i++) {
		print(dbgPaddingRight(t-&gt;columns[i]-&gt;displayName, columnLen[i]) . " | ");
	}
	println;

	for (i = 0; i &lt; t-&gt;columnCount; i++) {
		for (j = 0; j &lt; columnLen[i]; j++) {
			print("-");
		}
		print("-+-");
	}

	println;
	for (i = 0; i &lt; t-&gt;rowCount; i++) {
		for (j = 0; j &lt; t-&gt;columnCount; j++) {
			print(dbgPaddingRight(t-&gt;get(i, j), columnLen[j]) . " | ");
		}
		println;
	}

	println;
}
</code></pre>
<p dir="auto">Получение ячейки таблицы (по большей части для того, что бы использовать ячейку таблицы как DCI):</p>
<pre><code>// Warning: this script works only on the same node
//
// $1 - Description
// $2 - column name
table = GetDCIValueByDescription($node, $1);
if (table != NULL) {
	col = table-&gt;getColumnIndex($2);
	if (col &gt;= 0) {
		return table-&gt;get(0, col);
	}
}
return 0;
</code></pre>
]]></description><link>https://forum.netxms.org/post/20391</link><guid isPermaLink="true">https://forum.netxms.org/post/20391</guid><dc:creator><![CDATA[alk]]></dc:creator><pubDate>Fri, 08 Jul 2016 14:00:37 GMT</pubDate></item></channel></rss>