Merge remote-tracking branch 'origin/develop' into ent-4176-8084-8169-actualizacion-selenium-firefox-wux

Conflicts:
	pandora_console/extras/mr/37.sql
This commit is contained in:
fbsanchez 2020-04-14 16:06:17 +02:00
commit 7024863fd7
89 changed files with 10699 additions and 3197 deletions

View File

@ -1,5 +1,5 @@
package: pandorafms-agent-unix package: pandorafms-agent-unix
Version: 7.0NG.744-200413 Version: 7.0NG.744-200414
Architecture: all Architecture: all
Priority: optional Priority: optional
Section: admin Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
pandora_version="7.0NG.744-200413" pandora_version="7.0NG.744-200414"
echo "Test if you has the tools for to make the packages." echo "Test if you has the tools for to make the packages."
whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null

View File

@ -254,9 +254,6 @@ module_plugin pandora_mem_used
module_plugin pandora_netusage module_plugin pandora_netusage
# Service autodiscovery plugin
module_plugin autodiscover --default
# Plugin for inventory on the agent (Only Enterprise) # Plugin for inventory on the agent (Only Enterprise)
#module_plugin inventory 1 cpu ram video nic hd cdrom software init_services filesystem users route #module_plugin inventory 1 cpu ram video nic hd cdrom software init_services filesystem users route

View File

@ -55,7 +55,7 @@ my $Sem = undef;
my $ThreadSem = undef; my $ThreadSem = undef;
use constant AGENT_VERSION => '7.0NG.744'; use constant AGENT_VERSION => '7.0NG.744';
use constant AGENT_BUILD => '200413'; use constant AGENT_BUILD => '200414';
# Agent log default file size maximum and instances # Agent log default file size maximum and instances
use constant DEFAULT_MAX_LOG_SIZE => 600000; use constant DEFAULT_MAX_LOG_SIZE => 600000;

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_agent_unix %define name pandorafms_agent_unix
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
Summary: Pandora FMS Linux agent, PERL version Summary: Pandora FMS Linux agent, PERL version
Name: %{name} Name: %{name}

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_agent_unix %define name pandorafms_agent_unix
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
Summary: Pandora FMS Linux agent, PERL version Summary: Pandora FMS Linux agent, PERL version
Name: %{name} Name: %{name}

View File

@ -10,7 +10,7 @@
# ********************************************************************** # **********************************************************************
PI_VERSION="7.0NG.744" PI_VERSION="7.0NG.744"
PI_BUILD="200413" PI_BUILD="200414"
OS_NAME=`uname -s` OS_NAME=`uname -s`
FORCE=0 FORCE=0

View File

@ -245,10 +245,6 @@ module_plugin cscript.exe //B "%ProgramFiles%\Pandora_Agent\util\network.vbs"
#module_crontab * 12-15 * * 1 #module_crontab * 12-15 * * 1
#module_end #module_end
# Service autodiscovery plugin
module_plugin "%PROGRAMFILES%\Pandora_Agent\util\autodiscover.exe" --default
######################################### #########################################
# EXAMPLES # # EXAMPLES #
######################################### #########################################

View File

@ -186,7 +186,7 @@ UpgradeApplicationID
{} {}
Version Version
{200413} {200414}
ViewReadme ViewReadme
{Yes} {Yes}

View File

@ -30,7 +30,7 @@ using namespace Pandora;
using namespace Pandora_Strutils; using namespace Pandora_Strutils;
#define PATH_SIZE _MAX_PATH+1 #define PATH_SIZE _MAX_PATH+1
#define PANDORA_VERSION ("7.0NG.744(Build 200413)") #define PANDORA_VERSION ("7.0NG.744(Build 200414)")
string pandora_path; string pandora_path;
string pandora_dir; string pandora_dir;

View File

@ -11,7 +11,7 @@ BEGIN
VALUE "LegalCopyright", "Artica ST" VALUE "LegalCopyright", "Artica ST"
VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "OriginalFilename", "PandoraAgent.exe"
VALUE "ProductName", "Pandora FMS Windows Agent" VALUE "ProductName", "Pandora FMS Windows Agent"
VALUE "ProductVersion", "(7.0NG.744(Build 200413))" VALUE "ProductVersion", "(7.0NG.744(Build 200414))"
VALUE "FileVersion", "1.0.0.0" VALUE "FileVersion", "1.0.0.0"
END END
END END

View File

@ -1,2 +1,8 @@
# pandora disable listing # pandora disable listing
Options -Indexes Options -Indexes
<Files ~ "\.log$">
Order Allow,Deny
Deny from All
</Files>

View File

@ -1,5 +1,5 @@
package: pandorafms-console package: pandorafms-console
Version: 7.0NG.744-200413 Version: 7.0NG.744-200414
Architecture: all Architecture: all
Priority: optional Priority: optional
Section: admin Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
pandora_version="7.0NG.744-200413" pandora_version="7.0NG.744-200414"
package_pear=0 package_pear=0
package_pandora=1 package_pandora=1

View File

@ -2,6 +2,53 @@ START TRANSACTION;
ALTER TABLE tagente_modulo MODIFY COLUMN `custom_string_1` MEDIUMTEXT; ALTER TABLE tagente_modulo MODIFY COLUMN `custom_string_1` MEDIUMTEXT;
ALTER TABLE `trecon_task` MODIFY COLUMN `id_network_profile` TEXT;
ALTER TABLE `trecon_task` CHANGE COLUMN `create_incident` `review_mode` TINYINT(1) UNSIGNED DEFAULT 0;
ALTER TABLE `trecon_task` ADD COLUMN `subnet_csv` TINYINT(1) UNSIGNED DEFAULT 1;
UPDATE `trecon_task` SET `review_mode` = 1;
ALTER TABLE trecon_task add column `auto_monitor` TINYINT(1) UNSIGNED DEFAULT 1 AFTER `auth_strings`;
UPDATE `trecon_task` SET `auto_monitor` = 0;
CREATE TABLE `tdiscovery_tmp_agents` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`label` varchar(600) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`data` MEDIUMTEXT,
`review_date` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_rt` (`id_rt`),
INDEX `label` (`label`),
CONSTRAINT `tdta_trt` FOREIGN KEY (`id_rt`) REFERENCES `trecon_task` (`id_rt`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tdiscovery_tmp_connections` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`dev_1` text,
`dev_2` text,
`if_1` text,
`if_2` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tpen` (
`pen` int(10) unsigned NOT NULL,
`manufacturer` TEXT,
`description` TEXT,
PRIMARY KEY (`pen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `tnetwork_profile_pen` (
`pen` int(10) unsigned NOT NULL,
`id_np` int(10) unsigned NOT NULL,
CONSTRAINT `fk_network_profile_pen_pen` FOREIGN KEY (`pen`)
REFERENCES `tpen` (`pen`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_network_profile_pen_id_np` FOREIGN KEY (`id_np`)
REFERENCES `tnetwork_profile` (`id_np`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `twidget_dashboard` ADD COLUMN `position` TEXT NOT NULL default ''; ALTER TABLE `twidget_dashboard` ADD COLUMN `position` TEXT NOT NULL default '';
ALTER TABLE `tagente_estado` ADD COLUMN `last_status_change` bigint(20) NOT NULL default '0'; ALTER TABLE `tagente_estado` ADD COLUMN `last_status_change` bigint(20) NOT NULL default '0';
@ -12,4 +59,111 @@ ALTER TABLE `talert_templates` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0;
ALTER TABLE `tevent_alert` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0; ALTER TABLE `tevent_alert` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0;
ALTER TABLE `talert_snmp` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0; ALTER TABLE `talert_snmp` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0;
UPDATE twidget SET description='Show a visual console' WHERE class_name='MapsMadeByUser';
UPDATE twidget SET description='Clock' WHERE class_name='ClockWidget';
UPDATE twidget SET description='Group status' WHERE class_name='SystemGroupStatusWidget';
INSERT IGNORE INTO `tpen` VALUES (9,'cisco','Cisco&#x20;System'),(11,'hp','Hewlett&#x20;Packard'),(2021,'general_snmp','U.C.&#x20;Davis,&#x20;ECE&#x20;Dept.&#x20;Tom'),(2636,'juniper','Juniper&#x20;Networks'),(3375,'f5','F5&#x20;Labs'),(8072,'general_snmp','Net&#x20;SNMP'),(12356,'fortinet','Fortinet');
SET @template_name = 'Network&#x20;Management';
SET @template_description = 'Basic network monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Network Management')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Cisco&#x20;MIBS';
SET @template_description = 'Cisco devices monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Cisco MIBS' OR g.name = 'Catalyst 2900')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 9)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Linux&#x20;System';
SET @template_description = 'Linux system monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
SET @module_group = 'Linux';
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Linux' OR g.name = 'UCD Mibs (Linux, UCD-SNMP)')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 2021 OR p.pen = 2636)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;System';
SET @template_description = 'Windows system monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Microsoft&#x20;Windows' OR g.name = 'Windows System')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Hardware';
SET @template_description = 'Windows hardware monitoring templae (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Hardware Layer')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Active&#x20;Directory';
SET @template_description = 'Active directory monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows AD' OR g.name = 'AD&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;IIS';
SET @template_description = 'IIS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows IIS' OR g.name = 'IIS&#x20;services')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Exchange';
SET @template_description = 'Exchange monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Exchange' OR g.name = 'Exchange&#x20;Services' OR g.name = 'Exchange&#x20;TCP&#x20;Ports')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;LDAP';
SET @template_description = 'LDAP monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows LDAP')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MDSTC';
SET @template_description = 'MDSTC monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows MSDTC')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Printers';
SET @template_description = 'Windows printers monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Printers')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;DNS';
SET @template_description = 'Windows DNS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows&#x20;DNS' OR g.name = 'DNS&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MS&#x20;SQL&#x20;Server';
SET @template_description = 'MS SQL Server monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MS&#x20;SQL&#x20;Server')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Oracle';
SET @template_description = 'Oracle monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Oracle')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'MySQL';
SET @template_description = 'MySQL monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MySQL')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Antivirus';
SET @template_description = 'Windows antivirus monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Norton' OR g.name = 'Panda' OR g.name = 'McAfee' OR g.name = 'Bitdefender' OR g.name = 'BullGuard' OR g.name = 'AVG' OR g.name = 'Kaspersky')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
COMMIT; COMMIT;

View File

@ -1477,6 +1477,28 @@ ALTER TABLE tnetwork_component ADD COLUMN `dynamic_two_tailed` tinyint(1) unsign
ALTER TABLE `tnetwork_component` ADD COLUMN `ff_type` tinyint(1) unsigned default '0'; ALTER TABLE `tnetwork_component` ADD COLUMN `ff_type` tinyint(1) unsigned default '0';
ALTER TABLE `tnetwork_component` MODIFY COLUMN `ff_type` tinyint(1) unsigned NULL DEFAULT '0'; ALTER TABLE `tnetwork_component` MODIFY COLUMN `ff_type` tinyint(1) unsigned NULL DEFAULT '0';
-- ----------------------------------------------------------------------
-- Table `tpen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tpen` (
`pen` int(10) unsigned NOT NULL,
`manufacturer` TEXT,
`description` TEXT,
PRIMARY KEY (`pen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tnetwork_profile_pen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tnetwork_profile_pen` (
`pen` int(10) unsigned NOT NULL,
`id_np` int(10) unsigned NOT NULL,
CONSTRAINT `fk_network_profile_pen_pen` FOREIGN KEY (`pen`)
REFERENCES `tpen` (`pen`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_network_profile_pen_id_np` FOREIGN KEY (`id_np`)
REFERENCES `tnetwork_profile` (`id_np`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `tagente` -- Table `tagente`
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
@ -1662,7 +1684,39 @@ ALTER TABLE `trecon_task` ADD COLUMN `type` int(11) NOT NULL DEFAULT '0',
MODIFY COLUMN `wmi_enabled` tinyint(1) unsigned NULL DEFAULT '0', MODIFY COLUMN `wmi_enabled` tinyint(1) unsigned NULL DEFAULT '0',
MODIFY COLUMN `auth_strings` text NULL, MODIFY COLUMN `auth_strings` text NULL,
MODIFY COLUMN `autoconfiguration_enabled` tinyint(1) unsigned NULL DEFAULT '0', MODIFY COLUMN `autoconfiguration_enabled` tinyint(1) unsigned NULL DEFAULT '0',
MODIFY COLUMN `summary` text NULL; MODIFY COLUMN `summary` text NULL,
MODIFY COLUMN `id_network_profile` text,
CHANGE COLUMN `create_incident` `review_mode` TINYINT(1) UNSIGNED DEFAULT 1,
ADD COLUMN `subnet_csv` TINYINT(1) UNSIGNED DEFAULT 0;
-- Old recon always report.
UPDATE `trecon_task` SET `review_mode` = 1;
-- ----------------------------------------------------------------------
-- Table `tdiscovery_tmp`
-- ----------------------------------------------------------------------
CREATE TABLE `tdiscovery_tmp_agents` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`label` varchar(600) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`data` MEDIUMTEXT,
`review_date` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_rt` (`id_rt`),
INDEX `label` (`label`),
CONSTRAINT `tdta_trt` FOREIGN KEY (`id_rt`) REFERENCES `trecon_task` (`id_rt`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tdiscovery_tmp_connections` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`dev_1` text,
`dev_2` text,
`if_1` text,
`if_2` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `twidget` AND Table `twidget_dashboard` -- Table `twidget` AND Table `twidget_dashboard`
@ -2129,6 +2183,8 @@ ALTER TABLE `trecon_task` ADD COLUMN `snmp_auth_method` varchar(25) NOT NULL def
ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_method` varchar(25) NOT NULL default ''; ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_method` varchar(25) NOT NULL default '';
ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_pass` varchar(255) NOT NULL default ''; ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_pass` varchar(255) NOT NULL default '';
ALTER TABLE `trecon_task` ADD COLUMN `snmp_security_level` varchar(25) NOT NULL default ''; ALTER TABLE `trecon_task` ADD COLUMN `snmp_security_level` varchar(25) NOT NULL default '';
ALTER TABLE trecon_task add column `auto_monitor` TINYINT(1) UNSIGNED DEFAULT 1 AFTER `auth_strings`;
UPDATE `trecon_task` SET `auto_monitor` = 0;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `tagent_custom_fields_filter` -- Table `tagent_custom_fields_filter`
@ -2537,3 +2593,132 @@ INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `ma
INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;system&#x20;load','Current&#x20;load&#x20;&#40;5&#x20;min&#41;',43,34,0,0,300,0,'uptime&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;,&#039;','','','',6,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0); INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;system&#x20;load','Current&#x20;load&#x20;&#40;5&#x20;min&#41;',43,34,0,0,300,0,'uptime&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;,&#039;','','','',6,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0);
INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;memory&#x20;percent','Available&#x20;memory&#x20;%',43,34,0,0,300,0,'free&#x20;|&#x20;grep&#x20;Mem&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$NF/$2&#x20;*&#x20;100}&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'%','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0); INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;memory&#x20;percent','Available&#x20;memory&#x20;%',43,34,0,0,300,0,'free&#x20;|&#x20;grep&#x20;Mem&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$NF/$2&#x20;*&#x20;100}&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'%','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0);
INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;disk&#x20;/','Available&#x20;free&#x20;space&#x20;in&#x20;mountpoint&#x20;/',43,34,0,0,300,0,'df&#x20;/&#x20;|&#x20;tail&#x20;-n&#x20;+2&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;%&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'0.00',0.00,0.00,'',0,'','inherited','',0,0,0.000000000000000,'','nowizard','','nowizard','0','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0); INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;disk&#x20;/','Available&#x20;free&#x20;space&#x20;in&#x20;mountpoint&#x20;/',43,34,0,0,300,0,'df&#x20;/&#x20;|&#x20;tail&#x20;-n&#x20;+2&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;%&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'0.00',0.00,0.00,'',0,'','inherited','',0,0,0.000000000000000,'','nowizard','','nowizard','0','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0);
--
-- Dumping data for table `tpen`
--
INSERT IGNORE INTO `tpen`
VALUES
(9,'cisco','Cisco&#x20;System'),
(11,'hp','Hewlett&#x20;Packard'),
(2021,'general_snmp','U.C.&#x20;Davis,&#x20;ECE&#x20;Dept.&#x20;Tom'),
(2636,'juniper','Juniper&#x20;Networks'),
(3375,'f5','F5&#x20;Labs'),
(8072,'general_snmp','Net&#x20;SNMP'),
(12356,'fortinet','Fortinet')
;
--
-- Dumping data for table `tnetwork_profile` and `tnetwork_profile_pen`
--
SET @template_name = 'Network&#x20;Management';
SET @template_description = 'Basic network monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Network Management')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Cisco&#x20;MIBS';
SET @template_description = 'Cisco devices monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Cisco MIBS' OR g.name = 'Catalyst 2900')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 9)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Linux&#x20;System';
SET @template_description = 'Linux system monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
SET @module_group = 'Linux';
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Linux' OR g.name = 'UCD Mibs (Linux, UCD-SNMP)')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 2021 OR p.pen = 2636)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;System';
SET @template_description = 'Windows system monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Microsoft&#x20;Windows' OR g.name = 'Windows System')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Hardware';
SET @template_description = 'Windows hardware monitoring templae (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Hardware Layer')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Active&#x20;Directory';
SET @template_description = 'Active directory monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows AD' OR g.name = 'AD&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;IIS';
SET @template_description = 'IIS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows IIS' OR g.name = 'IIS&#x20;services')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Exchange';
SET @template_description = 'Exchange monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Exchange' OR g.name = 'Exchange&#x20;Services' OR g.name = 'Exchange&#x20;TCP&#x20;Ports')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;LDAP';
SET @template_description = 'LDAP monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows LDAP')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MDSTC';
SET @template_description = 'MDSTC monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows MSDTC')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Printers';
SET @template_description = 'Windows printers monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Printers')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;DNS';
SET @template_description = 'Windows DNS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows&#x20;DNS' OR g.name = 'DNS&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MS&#x20;SQL&#x20;Server';
SET @template_description = 'MS SQL Server monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MS&#x20;SQL&#x20;Server')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Oracle';
SET @template_description = 'Oracle monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Oracle')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'MySQL';
SET @template_description = 'MySQL monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MySQL')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Antivirus';
SET @template_description = 'Windows antivirus monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Norton' OR g.name = 'Panda' OR g.name = 'McAfee' OR g.name = 'Bitdefender' OR g.name = 'BullGuard' OR g.name = 'AVG' OR g.name = 'Kaspersky')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
-- Update widget.
UPDATE twidget SET description='Show a visual console' WHERE class_name='MapsMadeByUser';
UPDATE twidget SET description='Clock' WHERE class_name='ClockWidget';
UPDATE twidget SET description='Group status' WHERE class_name='SystemGroupStatusWidget';

View File

@ -137,11 +137,31 @@ if (!empty($sub)) {
$sub = []; $sub = [];
if (check_acl($config['id_user'], 0, 'PM')) { if (check_acl($config['id_user'], 0, 'PM')) {
$sub['godmode/modules/manage_network_components']['text'] = __('Network components'); // enterprise_hook('components_submenu');
$sub['godmode/modules/manage_network_components']['id'] = 'Network components'; $sub['templates']['text'] = __('Templates');
enterprise_hook('components_submenu'); $sub['templates']['id'] = 'Templates';
$sub['godmode/modules/manage_network_templates']['text'] = __('Module templates'); $sub['templates']['type'] = 'direct';
$sub['godmode/modules/manage_network_templates']['id'] = 'Module templates'; $sub['templates']['subtype'] = 'nolink';
$sub2 = [];
$sub2['godmode/modules/manage_module_templates']['text'] = __('Module templates');
$sub2['godmode/modules/manage_module_templates']['id'] = 'Module templates';
$sub2['godmode/modules/private_enterprise_numbers']['text'] = __('Private Enterprise Numbers');
$sub2['godmode/modules/private_enterprise_numbers']['id'] = 'Private Enterprise Numbers';
$sub2['enterprise/godmode/modules/local_components']['text'] = __('Local components');
$sub2['enterprise/godmode/modules/local_components']['id'] = 'Local components';
$sub2['godmode/modules/manage_network_components']['text'] = __('Remote components');
$sub2['godmode/modules/manage_network_components']['id'] = 'Network components';
$sub['templates']['sub2'] = $sub2;
/*
$sub2['godmode/modules/manage_snmp_modules']['text'] = __('SNMP Modules');
$sub2['godmode/modules/manage_snmp_modules']['id'] = 'SNMP Modules';
$sub2['godmode/modules/manage_wmi_modules']['text'] = __('WMI Modules');
$sub2['godmode/modules/manage_wmi_modules']['id'] = 'WMI Modules';
$sub['godmode/modules/manage_block_templates']['text'] = __('Module blocks');
$sub['godmode/modules/manage_block_templates']['id'] = 'Module blocks';
*/
enterprise_hook('inventory_submenu'); enterprise_hook('inventory_submenu');
enterprise_hook('autoconfiguration_menu'); enterprise_hook('autoconfiguration_menu');
enterprise_hook('agent_repository_menu'); enterprise_hook('agent_repository_menu');

View File

@ -0,0 +1,35 @@
<?php
// Pandora FMS - http://pandorafms.com
// ==================================================
// Copyright (c) 2005-2020 Artica Soluciones Tecnologicas
// Please see http://pandorafms.org for full contribution list
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation for version 2.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Load global vars
// TESTING
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/
// END
global $config;
check_login();
if (! check_acl($config['id_user'], 0, 'PM')) {
db_pandora_audit(
'ACL Violation',
'Trying to access Network Profile Management'
);
include 'general/noaccess.php';
return;
}
echo 'HOLA PRINCIPAL';

View File

@ -0,0 +1,68 @@
<?php
/**
* Module Templates management.
*
* @category Module templates management.
* @package Pandora FMS
* @subpackage Opensource
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2020 Artica Soluciones Tecnologicas
* Please see http://pandorafms.org for full contribution list
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation for version 2.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ============================================================================
*/
// Begin.
global $config;
require_once $config['homedir'].'/include/class/ModuleTemplates.class.php';
// This page.
$ajaxPage = 'godmode/modules/manage_module_templates';
// Control call flow.
try {
// User access and validation is being processed on class constructor.
$obj = new ModuleTemplates($ajaxPage);
} catch (Exception $e) {
if (is_ajax()) {
echo json_encode(['error' => '[ModuleTemplates]'.$e->getMessage() ]);
exit;
} else {
echo '[ModuleTemplates]'.$e->getMessage();
}
// Stop this execution, but continue 'globally'.
return;
}
// AJAX controller.
if (is_ajax()) {
$method = get_parameter('method');
if (method_exists($obj, $method) === true) {
$obj->{$method}();
} else {
$obj->error('Method not found. ['.$method.']');
}
// Stop any execution.
exit;
} else {
// Run.
$obj->run();
}

View File

@ -66,7 +66,7 @@ if (defined('METACONSOLE')) {
} }
ui_print_page_header( ui_print_page_header(
__('Module management').' &raquo; '.__('Network component management'), __('Module management').' &raquo; '.__('Remote component management'),
'', '',
false, false,
$help_header, $help_header,

View File

@ -45,8 +45,15 @@ ui_print_page_header(
true, true,
'modulemodal' 'modulemodal'
); );
/*
// At this moment, this message is not necessary
ui_print_info_message(
__(
'This section is maintained only for legacy use. Please, keep in mind use %s for manage template blocks.',
'<a href="'.ui_get_full_url('index.php?logged=1&sec=gmodules&sec2=godmode/modules/manage_block_templates').'">Module Blocks</a>'
)
);
*/
require_once 'include/functions_network_profiles.php'; require_once 'include/functions_network_profiles.php';
$delete_profile = (bool) get_parameter('delete_profile'); $delete_profile = (bool) get_parameter('delete_profile');

View File

@ -0,0 +1,68 @@
<?php
/**
* Private Enterprise Number managemtn.
*
* @category PEN management.
* @package Pandora FMS
* @subpackage Opensource
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2019 Artica Soluciones Tecnologicas
* Please see http://pandorafms.org for full contribution list
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation for version 2.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ============================================================================
*/
// Begin.
global $config;
require_once $config['homedir'].'/include/class/ConfigPEN.class.php';
// This page.
$ajaxPage = 'godmode/modules/private_enterprise_numbers';
// Control call flow.
try {
// User access and validation is being processed on class constructor.
$obj = new ConfigPEN($ajaxPage);
} catch (Exception $e) {
if (is_ajax()) {
echo json_encode(['error' => '[ConfigPEN]'.$e->getMessage() ]);
exit;
} else {
echo '[ConfigPEN]'.$e->getMessage();
}
// Stop this execution, but continue 'globally'.
return;
}
// AJAX controller.
if (is_ajax()) {
$method = get_parameter('method');
if (method_exists($obj, $method) === true) {
$obj->{$method}();
} else {
$obj->error('Method not found. ['.$method.']');
}
// Stop any execution.
exit;
} else {
// Run.
$obj->run();
}

View File

@ -1,5 +1,7 @@
<?php <?php
enterprise_include_once('include/functions_license.php');
global $config; global $config;
check_login(); check_login();
@ -48,6 +50,9 @@ function get_wiz_class($str)
case 'ctask': case 'ctask':
return 'ConsoleTasks'; return 'ConsoleTasks';
case 'deploymentCenter':
return 'DeploymentCenter';
default: default:
// Main, show header. // Main, show header.
ui_print_page_header( ui_print_page_header(
@ -124,13 +129,28 @@ $classname_selected = get_wiz_class($wiz_in_use);
// Else: class not found pseudo exception. // Else: class not found pseudo exception.
if ($classname_selected !== null) { if ($classname_selected !== null) {
$wiz = new $classname_selected($page); $wiz = new $classname_selected((int) $page);
$result = $wiz->run();
if (is_array($result) === true) { // AJAX controller.
// Redirect control and messages to DiscoveryTasklist. if (is_ajax()) {
$classname_selected = 'DiscoveryTaskList'; $method = get_parameter('method');
$wiz = new $classname_selected($page);
$result = $wiz->run($result['msg'], $result['result']); if (method_exists($wiz, $method) === true) {
$wiz->{$method}();
} else {
$wiz->error('Method not found. ['.$method.']');
}
// Stop any execution.
exit;
} else {
$result = $wiz->run();
if (is_array($result) === true) {
// Redirect control and messages to DiscoveryTasklist.
$classname_selected = 'DiscoveryTaskList';
$wiz = new $classname_selected($page);
$result = $wiz->run($result['msg'], $result['result']);
}
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* Extension to schedule tasks on Pandora FMS Console * Defines wizard to configure discovery tasks (Host&devices)
* *
* @category Wizard * @category Wizard
* @package Pandora FMS * @package Pandora FMS
@ -58,7 +58,6 @@ class HostDevices extends Wizard
public $pageLabelsNetScan = [ public $pageLabelsNetScan = [
'NetScan definition', 'NetScan definition',
'NetScan features', 'NetScan features',
]; ];
/** /**
@ -139,6 +138,8 @@ class HostDevices extends Wizard
// Load styles. // Load styles.
parent::run(); parent::run();
ui_require_css_file('hostdevices');
$mode = get_parameter('mode', null); $mode = get_parameter('mode', null);
if ($mode === null) { if ($mode === null) {
@ -269,6 +270,8 @@ class HostDevices extends Wizard
*/ */
public function parseNetScan() public function parseNetScan()
{ {
global $config;
if ($this->page == 0) { if ($this->page == 0) {
// Check if we're updating a task. // Check if we're updating a task.
$task_id = get_parameter('task', null); $task_id = get_parameter('task', null);
@ -297,9 +300,63 @@ class HostDevices extends Wizard
$comment = get_parameter('comment', ''); $comment = get_parameter('comment', '');
$server_id = get_parameter('id_recon_server', ''); $server_id = get_parameter('id_recon_server', '');
$network = get_parameter('network', ''); $network = get_parameter('network', '');
$network_csv_enabled = (bool) get_parameter_switch(
'network_csv_enabled',
false
);
$id_group = get_parameter('id_group', ''); $id_group = get_parameter('id_group', '');
$interval = get_parameter('interval', 0); $interval = get_parameter('interval', 0);
if ($network_csv_enabled) {
if (empty($_FILES['network_csv']['type']) === false) {
if ($_FILES['network_csv']['type'] != 'text/csv'
&& $_FILES['network_csv']['type'] != 'text/plain'
&& $_FILES['network_csv']['type'] != 'application/octet-stream'
&& $_FILES['network_csv']['type'] != 'application/vnd.ms-excel'
&& $_FILES['network_csv']['type'] != 'text/x-csv'
&& $_FILES['network_csv']['type'] != 'application/csv'
&& $_FILES['network_csv']['type'] != 'application/x-csv'
&& $_FILES['network_csv']['type'] != 'text/csv'
&& $_FILES['network_csv']['type'] != 'text/comma-separated-values'
&& $_FILES['network_csv']['type'] != 'text/x-comma-separated-values'
&& $_FILES['network_csv']['type'] != 'text/tab-separated-values'
) {
$this->msg = __(
'Invalid mimetype for csv file: %s',
$_FILES['network_csv']['type']
);
return false;
}
$network = preg_split(
"/\n|,|;/",
trim(
file_get_contents(
$_FILES['network_csv']['tmp_name']
)
)
);
unlink($_FILES['network_csv']['tmp_name']);
if (empty($network) || is_array($network) === false) {
$this->msg = __(
'Invalid content readed from csv file: %s',
$_FILES['network_csv']['name']
);
return false;
}
// Sanitize.
$network = array_unique($network);
$network = array_filter(
$network,
function ($item) {
return (!empty($item));
}
);
$network = join(',', $network);
}
}
if (isset($task_id) === true) { if (isset($task_id) === true) {
// We're updating this task. // We're updating this task.
$task = db_get_row( $task = db_get_row(
@ -333,18 +390,15 @@ class HostDevices extends Wizard
if ($task_id !== null if ($task_id !== null
&& $taskname == null && $taskname == null
&& $server_id == null && $server_id == null
&& $id_group == null && empty($id_group) === true
&& $server == null && empty($network) === true
&& $datacenter == '' && empty($network_csv) === true
&& $user == '' && $interval === 0
&& $pass == ''
&& $encrypt == null
&& $interval == 0
) { ) {
// Default values, no data received. // Default values, no data received.
// User is accesing directly to this page. // User is accesing directly to this page.
if (check_acl( if (check_acl(
$config['id_usuario'], $config['id_user'],
$this->task['id_group'], $this->task['id_group'],
$this->access $this->access
) != true ) != true
@ -386,6 +440,7 @@ class HostDevices extends Wizard
$this->task['id_recon_server'] = $server_id; $this->task['id_recon_server'] = $server_id;
$this->task['id_group'] = $id_group; $this->task['id_group'] = $id_group;
$this->task['interval_sweep'] = $interval; $this->task['interval_sweep'] = $interval;
$this->task['subnet_csv'] = $network_csv_enabled;
if (isset($this->task['id_rt']) === false) { if (isset($this->task['id_rt']) === false) {
// Create. // Create.
@ -423,7 +478,10 @@ class HostDevices extends Wizard
return false; return false;
} }
$id_network_profile = get_parameter('id_network_profile', null); $id_network_profile = get_parameter('id_network_profile', []);
$review_results = get_parameter_switch('review_results');
$review_limited = (bool) get_parameter('review_limited', 0);
$auto_monitor = get_parameter_switch('auto_monitor');
$autoconf_enabled = get_parameter_switch( $autoconf_enabled = get_parameter_switch(
'autoconfiguration_enabled' 'autoconfiguration_enabled'
); );
@ -443,7 +501,7 @@ class HostDevices extends Wizard
$snmp_privacy_pass = get_parameter('snmp_privacy_pass', null); $snmp_privacy_pass = get_parameter('snmp_privacy_pass', null);
$snmp_auth_method = get_parameter('snmp_auth_method', null); $snmp_auth_method = get_parameter('snmp_auth_method', null);
$snmp_security_level = get_parameter('snmp_security_level', null); $snmp_security_level = get_parameter('snmp_security_level', null);
$auth_strings = get_parameter('auth_strings', null); $auth_strings = get_parameter('auth_strings', []);
if ($snmp_version == 3) { if ($snmp_version == 3) {
$this->task['snmp_community'] = $snmp_context; $this->task['snmp_community'] = $snmp_context;
@ -452,7 +510,28 @@ class HostDevices extends Wizard
} }
$this->task['autoconfiguration_enabled'] = $autoconf_enabled; $this->task['autoconfiguration_enabled'] = $autoconf_enabled;
$this->task['id_network_profile'] = $id_network_profile; $this->task['id_network_profile'] = '';
if (is_array($id_network_profile) === true) {
$this->task['id_network_profile'] = join(
',',
$id_network_profile
);
}
if ($review_limited === true) {
// License limited, force review.
$this->task['review_mode'] = DISCOVERY_REVIEW;
} else {
if ($review_results) {
if ($this->task['review_mode'] != DISCOVERY_RESULTS) {
$this->task['review_mode'] = DISCOVERY_REVIEW;
}
} else {
$this->task['review_mode'] = DISCOVERY_STANDARD;
}
}
$this->task['auto_monitor'] = $auto_monitor;
$this->task['snmp_enabled'] = $snmp_enabled; $this->task['snmp_enabled'] = $snmp_enabled;
$this->task['os_detect'] = $os_detect; $this->task['os_detect'] = $os_detect;
$this->task['parent_detection'] = $parent_detection; $this->task['parent_detection'] = $parent_detection;
@ -467,7 +546,13 @@ class HostDevices extends Wizard
$this->task['snmp_privacy_pass'] = $snmp_privacy_pass; $this->task['snmp_privacy_pass'] = $snmp_privacy_pass;
$this->task['snmp_auth_method'] = $snmp_auth_method; $this->task['snmp_auth_method'] = $snmp_auth_method;
$this->task['snmp_security_level'] = $snmp_security_level; $this->task['snmp_security_level'] = $snmp_security_level;
$this->task['auth_strings'] = $auth_strings; $this->task['auth_strings'] = '';
if (is_array($auth_strings) === true) {
$this->task['auth_strings'] = join(
',',
$auth_strings
);
}
if ($this->task['disabled'] == 2) { if ($this->task['disabled'] == 2) {
// Wizard finished. // Wizard finished.
@ -562,7 +647,7 @@ class HostDevices extends Wizard
// Check ACL. If user is not able to manage target task, // Check ACL. If user is not able to manage target task,
// redirect him to main page. // redirect him to main page.
if (check_acl( if (check_acl(
$config['id_usuario'], $config['id_user'],
$this->task['id_group'], $this->task['id_group'],
$this->access $this->access
) != true ) != true
@ -598,10 +683,21 @@ class HostDevices extends Wizard
} }
if ($this->page < $this->maxPagesNetScan) { if ($this->page < $this->maxPagesNetScan) {
$title = __('NetScan');
if ($this->page == 1) {
$title = __(
'"%s" features',
io_safe_output(
$this->task['name']
)
);
}
// Avoid to print header out of wizard. // Avoid to print header out of wizard.
$this->prepareBreadcrum($breadcrum); $this->prepareBreadcrum($breadcrum);
ui_print_page_header( ui_print_page_header(
__('NetScan'), $title,
'', '',
false, false,
'', '',
@ -678,7 +774,7 @@ class HostDevices extends Wizard
$form['rows'][0]['columns'][0] = [ $form['rows'][0]['columns'][0] = [
'width' => '30%', 'width' => '30%',
'style' => 'padding: 9px;', 'style' => 'padding: 9px;min-width: 250px;',
'inputs' => [ 'inputs' => [
'0' => [ '0' => [
'arguments' => [ 'arguments' => [
@ -705,7 +801,10 @@ class HostDevices extends Wizard
'name' => 'interval_manual_defined', 'name' => 'interval_manual_defined',
'return' => true, 'return' => true,
], ],
'extra' => '<span id="interval_manual_container">'.html_print_extended_select_for_time( 'extra' => '<div id="interval_manual_container"><div class="time_selection_container">'.ui_print_help_tip(
__('The minimum recomended interval for Recon Task is 5 minutes'),
true
).html_print_extended_select_for_time(
'interval', 'interval',
$this->task['interval_sweep'], $this->task['interval_sweep'],
'', '',
@ -715,10 +814,7 @@ class HostDevices extends Wizard
true, true,
false, false,
false false
).ui_print_help_tip( ).'</div></div>',
__('The minimum recomended interval for Recon Task is 5 minutes'),
true
).'</span>',
], ],
], ],
@ -728,6 +824,7 @@ class HostDevices extends Wizard
'width' => '40%', 'width' => '40%',
'padding-right' => '12%', 'padding-right' => '12%',
'padding-left' => '5%', 'padding-left' => '5%',
'style' => 'min-width: 350px',
'inputs' => [ 'inputs' => [
'0' => [ '0' => [
'label' => '<b>'.__('Task name').':</b>', 'label' => '<b>'.__('Task name').':</b>',
@ -760,6 +857,54 @@ class HostDevices extends Wizard
], ],
], ],
'2' => [ '2' => [
'label' => '<b>'.__('Use CSV file definition').':</b>'.ui_print_help_tip(
__('Define targets using csv o network definition.'),
true
),
'class' => 'no-margin',
'arguments' => [
'name' => 'network_csv_enabled',
'value' => $this->task['subnet_csv'],
'type' => 'switch',
'inline' => true,
'class' => 'discovery_full_width_input',
'onclick' => 'toggleNetwork(this);',
],
],
'3' => [
'hidden' => (($this->task['subnet_csv'] == '1') ? 0 : 1),
'block_id' => 'csv_subnet',
'block_content' => [
[
'label' => '<b>'.__('Networks (csv)').':</b>'.ui_print_help_tip(
__('You can upload a CSV file. Each line must contain a network in IP/MASK format. For instance: 192.168.1.1/32'),
true
),
'arguments' => [
'name' => 'network_csv',
'type' => 'file',
'columns' => 25,
'rows' => 10,
'class' => 'discovery_full_width_input',
],
],
[
'label' => '<b>'.__('Networks (current)').':</b>'.ui_print_help_tip(
__('Plese upload a new file to overwrite this content.'),
true
),
'arguments' => [
'attributes' => 'readonly',
'type' => 'textarea',
'size' => 25,
'value' => $this->task['subnet'],
],
],
],
],
'4' => [
'hidden' => (($this->task['subnet_csv'] == '1') ? 1 : 0),
'id' => 'std_subnet',
'label' => '<b>'.__('Network').':</b>'.ui_print_help_tip( 'label' => '<b>'.__('Network').':</b>'.ui_print_help_tip(
__('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), __('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'),
true true
@ -794,6 +939,7 @@ class HostDevices extends Wizard
$form['rows'][0]['columns'][2] = [ $form['rows'][0]['columns'][2] = [
'width' => '30%', 'width' => '30%',
'style' => 'min-width: 250px',
'inputs' => ['0' => $group_select], 'inputs' => ['0' => $group_select],
]; ];
@ -823,8 +969,9 @@ class HostDevices extends Wizard
} }
$form['form'] = [ $form['form'] = [
'method' => 'POST', 'method' => 'POST',
'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url, 'enctype' => 'multipart/form-data',
'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url,
]; ];
// Default. // Default.
@ -848,7 +995,19 @@ class HostDevices extends Wizard
$("#hidden-interval").val('.$interval.'); $("#hidden-interval").val('.$interval.');
$("#interval_units").val('.$unit.'); $("#interval_units").val('.$unit.');
} }
}).change();'; }).change();
function toggleNetwork(e) {
if (e.checked) {
$(\'#csv_subnet\').removeClass("hidden");
$(\'#std_subnet\').addClass("hidden");
} else {
$(\'#csv_subnet\').addClass("hidden");
$(\'#std_subnet\').removeClass("hidden");
}
};
';
$this->printFormAsGrid($form); $this->printFormAsGrid($form);
$this->printGoBackButton($this->url.'&page='.($this->page - 1)); $this->printGoBackButton($this->url.'&page='.($this->page - 1));
@ -878,21 +1037,101 @@ class HostDevices extends Wizard
]; ];
$form['inputs'][] = [ $form['inputs'][] = [
'extra' => '<p><h3>Please, configure task <b>'.io_safe_output($this->task['name']).'</b></h3></p>', 'label' => __('Auto discover known hardware').ui_print_help_tip(
__(
'Targets will be monitorized based on its <i>Private Enterprise Number</i>. Requires SNMP.'
),
true
),
'arguments' => [
'name' => 'auto_monitor',
'type' => 'switch',
'return' => true,
'value' => (isset($this->task['auto_monitor'])) ? $this->task['auto_monitor'] : 1,
],
]; ];
$form['inputs'][] = [ $form['inputs'][] = [
'label' => __('Module template'), 'label' => __('Module templates').ui_print_help_tip(
__(
'Module <i>Host Alive</i> will be added to discovered agents by default.'
),
true
),
'arguments' => [ 'arguments' => [
'name' => 'id_network_profile', 'name' => 'id_network_profile[]',
'type' => 'select_from_sql', 'type' => 'select_from_sql',
'sql' => 'SELECT id_np, name 'sql' => 'SELECT tn.id_np, tn.name
FROM tnetwork_profile FROM tnetwork_profile tn
ORDER BY name', LEFT JOIN `tnetwork_profile_pen` tp
ON tp.id_np = tn.id_np
WHERE tp.id_np IS NULL
ORDER BY tn.name',
'return' => true, 'return' => true,
'selected' => $this->task['id_network_profile'], 'selected' => explode(
',',
$this->task['id_network_profile']
),
'nothing_value' => 0, 'nothing_value' => 0,
'nothing' => __('None'), 'nothing' => __('None'),
'multiple' => true,
'class' => 'select_multiple',
],
];
// License precheck.
$license = enterprise_hook('license_get_info');
$n_agents = 0;
foreach (explode(',', $this->task['subnet']) as $net) {
$mask = explode('/', $net, 2)[1];
if (empty($mask)) {
$n_agents++;
} else {
$n_agents += pow(2, (32 - $mask));
}
}
$limited = false;
if (is_array($license) === true
&& $n_agents > ($license['limit'] - $license['count'])
) {
$limit = ($license['limit'] - $license['count']);
$limited = true;
}
if ($limited === true) {
ui_print_warning_message(
__(
'Configured networks could generate %d agents, your license only allows %d, \'review results\' is mandatory.',
$n_agents,
$limit
)
);
}
$form['inputs'][] = [
'label' => __('Review results').ui_print_help_tip(
__(
'Targets must be validated by user before create agents.'
),
true
),
'arguments' => [
'name' => 'review_results',
'type' => 'switch',
'return' => true,
'value' => ($this->task['review_mode'] == DISCOVERY_STANDARD) ? (($limited) ? 1 : 0) : 1,
'disabled' => $limited,
],
];
// Review limited.
$form['inputs'][] = [
'arguments' => [
'name' => 'review_limited',
'type' => 'hidden',
'return' => true,
'value' => (($limited === true) ? 1 : 0),
], ],
]; ];
@ -930,7 +1169,7 @@ class HostDevices extends Wizard
// Submit button. // Submit button.
$form['inputs'][] = [ $form['inputs'][] = [
'arguments' => [ 'arguments' => [
'name' => 'submit', 'name' => 'submit-finish',
'label' => __('Finish'), 'label' => __('Finish'),
'type' => 'submit', 'type' => 'submit',
'attributes' => 'class="sub next"', 'attributes' => 'class="sub next"',

View File

@ -41,7 +41,7 @@ class Wizard
/** /**
* Breadcrum * Breadcrum
* *
* @var array. * @var array
*/ */
public $breadcrum; public $breadcrum;
@ -233,6 +233,27 @@ class Wizard
} }
/**
* Return formatted html for error handler.
*
* @param string $message Error mesage.
*
* @return string
*/
public function error($message)
{
if (is_ajax()) {
echo json_encode(
[
'error' => ui_print_error_message($message, '', true),
]
);
} else {
return ui_print_error_message($message, '', true);
}
}
/** /**
* To be overwritten. * To be overwritten.
* *
@ -566,66 +587,40 @@ class Wizard
if (is_array($input['block_content']) === true) { if (is_array($input['block_content']) === true) {
// Print independent block of inputs. // Print independent block of inputs.
$output .= '<li id="'.$input['block_id'].'" class="'.$class.'">'; $output .= '<div id="'.$input['block_id'].'" class="wizard '.$class.'">';
$output .= '<ul class="wizard '.$input['block_class'].'">'; $output .= '<ul class="wizard '.$input['block_class'].'">';
foreach ($input['block_content'] as $input) { foreach ($input['block_content'] as $input) {
$output .= $this->printBlockAsGrid($input, $return); $output .= $this->printBlockAsGrid($input, $return);
} }
$output .= '</ul></li>'; $output .= '</ul></div>';
} else { } else {
if ($input['arguments']['type'] != 'hidden' if ($input['arguments']['type'] != 'hidden'
&& $input['arguments']['type'] != 'hidden_extended' && $input['arguments']['type'] != 'hidden_extended'
) { ) {
if ($input['arguments']['inline'] != 'true') { $id = '';
$output .= '<div class="edit_discovery_input">'; if ($input['id']) {
} else { $id = $input['id'];
$output .= '<div style="display: flex; margin-bottom: 25px; flex-wrap: wrap;">';
if (!isset($input['extra'])) {
$output .= '<div style="width: 50%;">';
}
if (isset($input['extra'])) {
$output .= '<div style="display: flex; margin-right:10px;">';
}
} }
if ($input['arguments']['inline'] == 'true' && isset($input['extra'])) { if ($input['arguments']['inline'] != 'true') {
$output .= '<div style="margin-right:10px;">'; $output .= '<div id="'.$id.'" class="std_input '.$class.'">';
} else {
$output .= '<div id="'.$id.'" class="inline_input '.$class.'">';
} }
$output .= '<div class="label_select">'; $output .= '<div class="label_select">';
$output .= $input['label']; $output .= $input['label'];
$output .= '</div>'; $output .= '</div>';
if ($input['arguments']['inline'] == 'true' && isset($input['extra'])) {
$output .= '</div>';
}
if ($input['arguments']['inline'] == 'true' && !isset($input['extra'])) {
$output .= '</div>';
}
if ($input['arguments']['type'] == 'text' || $input['arguments']['type'] == 'text_extended') { if ($input['arguments']['type'] == 'text' || $input['arguments']['type'] == 'text_extended') {
$output .= '<div class="discovery_text_input">'; $output .= '<div class="discovery_text_input">';
$output .= $this->printInput($input['arguments']); $output .= $this->printInput($input['arguments']);
$output .= '</div>'; $output .= '</div>';
} else if ($input['arguments']['inline'] == 'true') { } else if ($input['arguments']['inline'] == 'true') {
if (isset($input['extra'])) { $output .= '<div class="discovery_inline_input">';
$output .= '<div style="">';
$output .= '<div style="float: left;">';
} else {
$output .= '<div style="width:50%;">';
$output .= '<div style="float: right;">';
}
$output .= $this->printInput($input['arguments']); $output .= $this->printInput($input['arguments']);
$output .= '</div>'; $output .= '</div>';
$output .= '</div>';
if (isset($input['extra'])) {
$output .= '</div>';
}
} else { } else {
$output .= $this->printInput($input['arguments']); $output .= $this->printInput($input['arguments']);
} }
@ -800,7 +795,7 @@ class Wizard
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
$cb_args = $data['cb_args']; $cb_args = $data['cb_args'];
$output_head = '<form class="discovery" onsubmit="'.$form['onsubmit'].'" enctype="'.$form['enctype'].'" action="'.$form['action'].'" method="'.$form['method']; $output_head = '<form class="discovery wizard" onsubmit="'.$form['onsubmit'].'" enctype="'.$form['enctype'].'" action="'.$form['action'].'" method="'.$form['method'];
$output_head .= '" '.$form['extra'].'>'; $output_head .= '" '.$form['extra'].'>';
if ($return === false) { if ($return === false) {

View File

@ -24,154 +24,7 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* ============================================================================ * ============================================================================
*
*
* MOVED TO DiscoveryTaskList.class.
*/ */
require_once $config['homedir'].'/include/graphs/functions_d3.php';
$progress_task_discovery = (bool) get_parameter('progress_task_discovery', 0);
$showmap = (bool) get_parameter('showmap', 0);
if ($progress_task_discovery) {
$id_task = get_parameter('id', 0);
if ($id_task <= 0) {
echo json_encode(['error' => true]);
return;
}
$task = db_get_row('trecon_task', 'id_rt', $id_task);
$global_progress = $task['status'];
$summary = json_decode($task['summary'], true);
$result = '<div id = progress_task_'.$id_task.'>';
if ($task['utimestamp']) {
$result .= '<div style="display: flex;">';
$result .= '<div style="width: 100%; text-align: center; margin-top: 40px;">';
$result .= '<span style="font-size: 1.9em; font-family: "lato-bolder", "Open Sans", sans-serif !important;">'._('Overall Progress').'</span>';
$result .= '<div style="margin-top: 25px;">';
$result .= progress_circular_bar(
$id_task,
($global_progress < 0) ? 100 : $global_progress,
200,
200,
'#7eb641',
'%',
'',
'#3A3A3A',
0
);
$result .= '</div>';
if ($global_progress > 0) {
switch ($summary['step']) {
case STEP_SCANNING:
$str = __('Scanning network');
break;
case STEP_AFT:
$str = __('Finding AFT connectivity');
break;
case STEP_TRACEROUTE:
$str = __('Finding traceroute connectivity');
break;
case STEP_GATEWAY:
$str = __('Finding gateway connectivity');
break;
default:
$str = __('Searching for devices...');
break;
}
$result .= '</div>';
$result .= '<div style="width: 100%; text-align: center; margin-top: 40px;">';
$result .= '<span style="font-size: 1.9em; font-family: "lato-bolder", "Open Sans", sans-serif !important;">'.$str.' ';
$result .= $summary['c_network_name'];
$result .= '</span>';
$result .= '<div style="margin-top: 25px;">';
$result .= progress_circular_bar(
$id_task.'_detail',
$summary['c_network_percent'],
200,
200,
'#7eb641',
'%',
'',
'#3A3A3A',
0
);
$result .= '</div></div>';
}
$result .= '</div></div>';
$i = 0;
$table = new StdClasS();
$table->class = 'databox data';
$table->width = '75%';
$table->styleTable = 'margin: 2em auto 0;border: 1px solid #ddd;background: white;';
$table->rowid = [];
$table->data = [];
// Content.
$table->data[$i][0] = '<b>'.__('Hosts discovered').'</b>';
$table->data[$i][1] = '<span id="discovered">';
$table->data[$i][1] .= $summary['summary']['discovered'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Alive').'</b>';
$table->data[$i][1] = '<span id="alive">';
$table->data[$i][1] .= $summary['summary']['alive'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Not alive').'</b>';
$table->data[$i][1] = '<span id="not_alive">';
$table->data[$i][1] .= $summary['summary']['not_alive'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Responding SNMP').'</b>';
$table->data[$i][1] = '<span id="SNMP">';
$table->data[$i][1] .= $summary['summary']['SNMP'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Responding WMI').'</b>';
$table->data[$i][1] = '<span id="WMI">';
$table->data[$i][1] .= $summary['summary']['WMI'];
$table->data[$i++][1] .= '</span>';
$result .= '<div style="margin-top: 40px; text-align: center;"><span style="font-size: 1.9em; font-family: "lato-bolder", "Open Sans", sans-serif !important;">'.__('Summary').'</span></div>';
$result .= html_print_table($table, true).'</div>';
} else {
$global_progress = -1;
$result .= ui_print_error_message(
__('No data to show'),
'',
true
).'</div>';
}
$result_array['status'] = $global_progress;
$result_array['html'] = $result;
echo json_encode($result_array);
return;
}
if ($showmap) {
include_once $config['homedir'].'/include/class/NetworkMap.class.php';
$id_task = get_parameter('id', 0);
$map = new NetworkMap(
[
'id_task' => $id_task,
'pure' => 1,
'widget' => true,
]
);
$map->printMap();
}

View File

@ -0,0 +1,782 @@
<?php
/**
* Agent Wizard for SNMP and WMI
*
* @category Class
* @package Pandora FMS
* @subpackage Agent Configuration
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2020 Artica Soluciones Tecnologicas
* Please see http://pandorafms.org for full contribution list
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation for version 2.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ============================================================================
*/
// Get global data.
global $config;
// Necessary class for extends.
require_once $config['homedir'].'/include/class/HTML.class.php';
/**
* AgentWizard class
*/
class AgentWizard extends HTML
{
/**
* Var that contain very cool stuff
*
* @var string
*/
private $ajaxController;
/**
* Contains the URL of this
*
* @var string
*/
private $baseUrl;
/**
* Id of this current agent
*
* @var integer
*/
private $idAgent;
/**
* Wizard Section for Explore
*
* @var string
*/
private $wizardSection;
/**
* Label to show what action are performing
*
* @var string
*/
private $actionLabel;
/**
* Type of action to do
*
* @param string
*/
private $actionType;
/**
* Constructor
*
* @param string $ajax_controller Pues hace cosas to wapas.
*/
public function __construct(string $ajax_controller)
{
global $config;
// Check access.
check_login();
if (! check_acl($config['id_user'], 0, 'AR')) {
db_pandora_audit(
'ACL Violation',
'Trying to access event viewer'
);
if (is_ajax()) {
echo json_encode(['error' => 'noaccess']);
}
include 'general/noaccess.php';
exit;
}
// Set baseUrl for use it in several locations in this class.
$this->baseUrl = ui_get_full_url('index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=agent_wizard');
// Capture all parameters before start.
$this->ajaxController = $ajax_controller;
$this->wizardSection = get_parameter('wizard_section', '');
$this->idAgent = get_parameter('id_agente', '');
return $this;
}
/**
* Run main page.
*
* @return void
*/
public function run()
{
// CSS.
ui_require_css_file('wizard');
ui_require_css_file('discovery');
// Javascript.
// ui_require_javascript_file('jquery.caret.min');
$this->loadMainForm();
$this->performWizard();
// Load integrated JS
$this->loadJS();
}
/**
* Common Main Wizard form
*
* @return void
*/
private function loadMainForm()
{
// Define name of explorer button
switch ($this->wizardSection) {
case 'snmp_explorer':
case 'snmp_interfaces_explorer':
// Define labels.
$this->actionType = 'snmp';
$this->actionLabel = __('SNMP Walk');
// Fill with servers to perform SNMP walk.
$fieldsServers = [];
$fieldsServers[0] = __('Local console');
if (enterprise_installed()) {
enterprise_include_once('include/functions_satellite.php');
// Get the servers.
$rows = get_proxy_servers();
// Check if satellite server has remote configuration enabled.
$satellite_remote = config_agents_has_remote_configuration($this->idAgent);
// Generate a list with allowed servers.
foreach ($rows as $row) {
if ($row['server_type'] == 13) {
$id_satellite = $row['id_server'];
$serverType = ' (Satellite)';
} else {
$serverType = ' (Standard)';
}
$fieldsServers[$row['id_server']] = $row['name'].$serverType;
}
}
// Fill with SNMP versions allowed.
$fieldsVersions = [
'1' => '1',
'2' => '2',
'2c' => '2c',
'3' => '3',
];
break;
case 'wmi_explorer':
$this->actionType = 'wmi';
$this->actionLabel = __('WMI Explorer');
break;
default:
$this->actionType = 'none';
$this->actionLabel = __('Nothing');
exit;
break;
}
// Main form.
$form = [
'action' => '',
// 'action' => $this->baseUrl,
'id' => 'main_wizard_form',
'method' => 'POST',
];
// Inputs.
$inputs = [];
$inputs[] = [
'id' => 'hdn-type-action',
'arguments' => [
'name' => 'type-action',
'type' => 'hidden',
'value' => $this->actionType,
'return' => true,
],
];
$inputs[] = [
'label' => __('Target IP'),
'id' => 'txt-target-ip',
'arguments' => [
'name' => 'target-ip',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('Port'),
'id' => 'txt-target-port',
'arguments' => [
'name' => 'target-port',
'input_class' => 'flex-row',
'type' => 'text',
'size' => '20',
'class' => '',
'return' => true,
],
];
if ($this->actionType === 'snmp') {
$inputs[] = [
'label' => __('Use agent IP'),
'id' => 'txt-use-agent-ip',
'arguments' => [
'name' => 'use-agent-ip',
'input_class' => 'flex-row',
'type' => 'checkbox',
'class' => '',
'return' => true,
],
];
}
if ($this->actionType === 'wmi') {
$inputs[] = [
'label' => __('Namespace'),
'id' => 'txt-namespace',
'arguments' => [
'name' => 'namespace',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('Username'),
'id' => 'txt-username',
'arguments' => [
'name' => 'username',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('Password'),
'id' => 'txt-password',
'arguments' => [
'name' => 'password',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
}
$inputs[] = [
'label' => __('Server to execute command'),
'id' => 'txt-target-port',
'arguments' => [
'name' => 'target-port',
'input_class' => 'flex-row',
'type' => 'select',
'fields' => $fieldsServers,
'class' => '',
'return' => true,
],
];
if ($this->actionType === 'snmp') {
$inputs[] = [
'label' => __('SNMP community'),
'id' => 'txt-snmp-community',
'arguments' => [
'name' => 'snmp-community',
'input_class' => 'flex-row',
'type' => 'text',
'size' => '20',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('SNMP version'),
'id' => 'txt-snmnp-version',
'arguments' => [
'name' => 'snmnp-version',
'input_class' => 'flex-row',
'type' => 'select',
'fields' => $fieldsVersions,
'class' => '',
'return' => true,
],
];
}
$inputs[] = [
'arguments' => [
'label' => $this->actionLabel,
'name' => 'action',
'type' => 'submit',
'attributes' => 'class="sub next" onclick="performAction();return false;"',
'return' => true,
],
];
// Prints main form.
html_print_div(
[
'class' => 'white_box',
'content' => $this->printForm(
[
'form' => $form,
'inputs' => $inputs,
],
true
),
]
);
}
/**
* Undocumented function
*
* @return void
*/
public function performWizard()
{
// echo json_encode(['error' => obhd($_REQUEST)]);
// exit;
$sql = sprintf(
'SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS `group`, ncg.name AS `group_name`
FROM tnetwork_profile_component AS npc, tnetwork_component AS nc
INNER JOIN tnetwork_component_group AS ncg ON ncg.id_sg = nc.id_group
WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d',
10
);
$moduleBlocks = db_get_all_rows_sql($sql);
$blockTables = [];
// Build the information of the blocks.
foreach ($moduleBlocks as $block) {
if (key_exists($block['group'], $blockTables) === false) {
$blockTables[$block['group']] = [
'name' => $block['group_name'],
'data' => [],
];
}
$blockTables[$block['group']]['data'][] = [
'component_id' => $block['component_id'],
'name' => $block['name'],
'type' => $block['type'],
'description' => $block['description'],
];
}
// Lets generate the block tables.
$output = '';
foreach ($blockTables as $id_group => $blockTable) {
// Data with all components.
$blockData = $blockTable['data'];
// Creation of list of all components.
$blockComponentList = '';
foreach ($blockData as $component) {
$blockComponentList .= $component['component_id'].',';
}
$blockComponentList = chop($blockComponentList, ',');
// Title of Block.
$blockTitle = $blockTable['name'];
$blockTitle .= html_print_div(
[
'class' => 'white_table_header_checkbox',
'content' => html_print_checkbox_switch_extended(
'sel_block_'.$id_group,
1,
0,
false,
'switchBlockControl(event)',
'',
true
),
],
true
);
$table = new StdClasS();
$table->class = 'databox data';
$table->width = '75%';
$table->styleTable = 'margin: 2em auto 0;border: 1px solid #ddd;background: white;';
$table->rowid = [];
$table->data = [];
$table->cellpadding = 0;
$table->cellspacing = 0;
$table->width = '100%';
$table->class = 'info_table';
$table->head = [];
$table->head[0] = html_print_div(['style' => 'font-weight:700;', 'content' => __('Module Name')], true);
$table->head[1] = html_print_div(['style' => 'font-weight:700;text-align:center;', 'content' => __('Type')], true);
$table->head[2] = html_print_div(['style' => 'font-weight:700;', 'content' => __('Module info')], true);
$table->head[3] = html_print_div(['style' => 'font-weight:700;text-align:center;', 'content' => __('Warning')], true);
$table->head[4] = html_print_div(['style' => 'font-weight:700;text-align:center;', 'content' => __('Critical')], true);
$table->head[5] = html_print_div(['style' => 'font-weight:700;margin-right:1.2em;', 'content' => __('Active')], true);
$table->size = [];
$table->size[0] = '15%';
$table->size[1] = '3%';
$table->size[3] = '210px';
$table->size[4] = '210px';
$table->size[5] = '3%';
$table->align = [];
$table->align[5] = 'right';
$table->data = [];
foreach ($blockData as $module) {
// Module Name column.
$data[0] = $module['name'];
// Module Type column.
$data[1] = ui_print_moduletype_icon($module['type'], true);
// Module info column.
$data[2] = mb_strimwidth(io_safe_output($module['description']), 0, 150, '...');
// Warning column.
$data[3] = html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Min: '.html_print_input_text(
'warning_min_'.$module['component_id'],
'0',
'',
3,
4,
true
).' ',
],
true
);
$data[3] .= html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Max: '.html_print_input_text(
'warning_max_'.$module['component_id'],
'0',
'',
3,
4,
true
),
],
true
);
$data[3] .= html_print_div(
[
'class' => 'wizard-column-levels',
'style' => 'margin-top: 0.3em;',
'content' => 'Inv: '.html_print_checkbox(
'warning_inv_'.$module['component_id'],
0,
false,
true,
false
),
],
true
);
// Critical column.
$data[4] = html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Min: '.html_print_input_text(
'critical_min_'.$module['component_id'],
'0',
'',
3,
4,
true
).' ',
],
true
);
$data[4] .= html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Max: '.html_print_input_text(
'critical_max_'.$module['component_id'],
'0',
'',
3,
4,
true
),
],
true
);
$data[4] .= html_print_div(
[
'class' => 'wizard-column-levels',
'style' => 'margin-top: 0.3em;',
'content' => 'Inv: '.html_print_checkbox(
'critical_inv_'.$module['component_id'],
0,
false,
true,
false
),
],
true
);
// Activation column.
$data[5] = html_print_checkbox_switch_extended('sel_module_'.$id_group.'_'.$module['component_id'], 1, 0, false, 'switchBlockControl(event)', '', true);
array_push($table->data, $data);
}
$content = html_print_table($table, true);
$output .= ui_toggle($content, $blockTitle, '', '', false, true);
}
html_print_div(
[
'class' => 'white_box',
'style' => 'margin-top: 20px;',
'content' => $output,
]
);
// Form. Not used at this moment.
$form = [
'action' => $this->baseUrl,
'id' => 'modal_form_action_response',
'method' => 'POST',
'class' => 'modal',
'extra' => '',
];
// Inputs.
$inputs = [];
$inputs[] = [
'id' => 'inp-id_np',
'arguments' => [
'name' => 'id_np',
'type' => 'hidden',
'value' => '69',
'return' => true,
],
];
$this->printForm(
[
'form' => $form,
'inputs' => $inputs,
true
]
);
}
/**
* Perform SNMP
*
* @return void
*/
private function performSNMP()
{
echo 'HOLA';
}
/**
* Perform WMI
*
* @return void
*/
private function performWMI()
{
}
/**
* Generate the JS needed for use inside
*
* @return void
*/
private function loadJS()
{
$str = '';
ob_start();
?>
<script type="text/javascript">
// The functions goes here!
/**
* WIP: Loads modal from AJAX to perform the required action.
*/
function performAction() {
var btn_ok_text = '<?php echo __('OK'); ?>';
var btn_cancel_text = '<?php echo __('Cancel'); ?>';
var title = '<?php echo __('Perform %s', $this->actionLabel); ?>';
var action = '<?php echo $this->actionType; ?>';
console.log(title);
console.log(action);
load_modal({
target: $('#modal'),
form: 'modal_form_action_response',
url: '<?php echo ui_get_full_url('ajax.php', false, false, false); ?>',
ajax_callback: showMsg,
modal: {
title: title,
ok: btn_ok_text,
cancel: btn_cancel_text,
},
/* extradata: [
{
name: 'action',
value: action,
}
], */
onshow: {
page: '<?php echo $this->ajaxController; ?>',
method: 'performWizard'
}/* ,
onsubmit: {
page: '<?//php echo $this->ajaxController; ?>',
method: 'processData'
} */
});
console.log("he terminado");
}
/**
* WIP: Process ajax responses and shows a dialog with results.
*/
function showMsg(data) {
var title = "<?php echo __('Success'); ?>";
var text = "";
var failed = 0;
try {
data = JSON.parse(data);
text = data["result"];
} catch (err) {
title = "<?php echo __('Failed'); ?>";
text = err.message;
failed = 1;
}
if (!failed && data["error"] != undefined) {
title = "<?php echo __('Failed'); ?>";
text = data["error"];
failed = 1;
}
if (data["report"] != undefined) {
data["report"].forEach(function(item) {
text += "<br>" + item;
});
}
$("#msg").empty();
$("#msg").html(text);
$("#msg").dialog({
width: 450,
position: {
my: "center",
at: "center",
of: window,
collision: "fit"
},
title: title,
buttons: [
{
class:
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
text: "OK",
click: function(e) {
}
}
]
});
}
/**
* Controls checkboxes for modules
*/
function switchBlockControl(e) {
var switchId = e.target.id.split("_");
var type = switchId[1];
var blockNumber = switchId[2];
var selectedBlock = $("#checkbox-sel_block_" + blockNumber);
var totalCount = 0;
var markedCount = 0;
if (type == 'block') {
if (selectedBlock.prop("checked")) {
$("[id*=checkbox-sel_module_" + blockNumber + "]").each(function(){
$(this).prop("checked", true);
});
} else {
$("[id*=checkbox-sel_module_" + blockNumber + "]").each(function(){
$(this).prop("checked", false);
});
}
} else if (type == 'module') {
$("[id*=checkbox-sel_module_" + blockNumber + "]").each(function() {
if ($(this).prop("checked")) {
markedCount++;
}
totalCount++;
});
if (totalCount == markedCount) {
selectedBlock.prop("checked", true);
selectedBlock
.parent()
.removeClass("alpha50");
} else if (markedCount == 0) {
selectedBlock.prop("checked", false);
selectedBlock
.parent()
.removeClass("alpha50");
} else {
selectedBlock.prop("checked", true);
selectedBlock
.parent()
.addClass("alpha50");
}
}
}
</script>
<?php
$str = ob_get_clean();
echo $str;
return $str;
}
}

View File

@ -0,0 +1,799 @@
<?php
/**
* PEN Configuration feature.
*
* @category Class
* @package Pandora FMS
* @subpackage Wizard Setup
* @version 0.0.1
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2020 Artica Soluciones Tecnologicas
* Please see http://pandorafms.org for full contribution list
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation for version 2.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ============================================================================
*/
global $config;
require_once $config['homedir'].'/include/class/HTML.class.php';
/**
* Config PEN Class
*/
class ConfigPEN extends HTML
{
/**
* Url of controller.
*
* @var string
*/
public $ajaxController;
/**
* URL Base
*
* @var string
*/
private $baseUrl;
/**
* Contructor.
*
* @param string $ajax_page Target ajax page.
*/
public function __construct($ajax_page)
{
global $config;
// Check access.
check_login();
if (! check_acl($config['id_user'], 0, 'PM')) {
db_pandora_audit(
'ACL Violation',
'Trying to access PEN Definition feature'
);
include 'general/noaccess.php';
exit;
}
$this->ajaxController = $ajax_page;
$this->offset = '';
$this->baseUrl = ui_get_full_url(
'index.php?sec=configuration_wizard_setup&sec2=godmode/modules/private_enterprise_numbers'
);
}
/**
* Returns an array with all the credentials matching filter and ACL.
*
* @param array $fields Fields array or 'count' keyword to retrieve count.
* @param array $filter Filters to be applied.
* @param integer $offset Offset (pagination).
* @param integer $limit Limit (pagination).
* @param string $order Sort order.
* @param string $sort_field Sort field.
*
* @return array With all results or false if error.
* @throws Exception On error.
*/
public static function getAll(
$fields,
$filter=null,
$offset=null,
$limit=null,
$order=null,
$sort_field=null
) {
$sql_filters = [];
$order_by = '';
$pagination = '';
$count = false;
if (!is_array($fields) && $fields == 'count') {
$fields = ['*'];
$count = true;
} else if (!is_array($fields)) {
error_log('[configPEN.getAll] Fields must be an array or "count".');
throw new Exception('[configPEN.getAll] Fields must be an array or "count".');
}
if (is_array($filter)) {
if (!empty($filter['free_search'])) {
$sql_filters[] = vsprintf(
' AND (lower(`manufacturer`) like lower("%%%s%%")
OR pen = "%s") ',
array_fill(0, 2, $filter['free_search'])
);
}
if (!empty($filter['pen'])) {
$sql_filters[] = sprintf(
' AND `pen` = %d',
$filter['pen']
);
}
}
if (isset($order)) {
$dir = 'asc';
if ($order == 'desc') {
$dir = 'desc';
};
if (in_array(
$sort_field,
[
'pen',
'manufacturer',
'description',
]
)
) {
$order_by = sprintf(
'ORDER BY `%s` %s',
$sort_field,
$dir
);
}
}
if (isset($limit) && $limit > 0
&& isset($offset) && $offset >= 0
) {
$pagination = sprintf(
' LIMIT %d OFFSET %d ',
$limit,
$offset
);
}
$sql = sprintf(
'SELECT %s
FROM `tpen`
WHERE 1=1
%s
%s
%s',
join(',', $fields),
join(' ', $sql_filters),
$order_by,
$pagination
);
if ($count) {
$sql = sprintf('SELECT count(*) as n FROM ( %s ) tt', $sql);
return db_get_value_sql($sql);
}
return db_get_all_rows_sql($sql);
}
/**
* AJAX: Return JSON content for datatable.
*
* @return void
*/
function draw()
{
global $config;
// Datatables offset, limit and order.
$filter = get_parameter('filter', []);
$start = get_parameter('start', 0);
$length = get_parameter('length', $config['block_size']);
$order = get_datatable_order(true);
try {
ob_start();
$fields = ['*'];
// Retrieve data.
$data = $this->getAll(
// Fields.
$fields,
// Filter.
$filter,
// Offset.
$start,
// Limit.
$length,
// Order.
$order['direction'],
// Sort field.
$order['field']
);
// Retrieve counter.
$count = $this->getAll(
'count',
$filter
);
if ($data) {
$data = array_reduce(
$data,
function ($carry, $item) {
// Transforms array of arrays $data into an array
// of objects, making a post-process of certain fields.
$tmp = (object) $item;
$tmp->description = io_safe_output($tmp->description);
$tmp->manufacturer = io_safe_output($tmp->manufacturer);
$tmp->options = '';
$tmp->options = '<a href="javascript:" onclick="showForm(\'';
$tmp->options .= $tmp->pen;
$tmp->options .= '\')" >';
$tmp->options .= html_print_image(
'images/eye.png',
true,
['title' => __('Show')]
);
$tmp->options .= '</a>';
$tmp->options .= '<a href="javascript:" onclick="deletePEN(\'';
$tmp->options .= $tmp->pen;
$tmp->options .= '\')" >';
$tmp->options .= html_print_image(
'images/cross.png',
true,
['title' => __('Delete')]
);
$tmp->options .= '</a>';
$carry[] = $tmp;
return $carry;
}
);
}
// Datatables format: RecordsTotal && recordsfiltered.
echo json_encode(
[
'data' => $data,
'recordsTotal' => $count,
'recordsFiltered' => $count,
]
);
// Capture output.
$response = ob_get_clean();
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
exit;
}
// If not valid, show error with issue.
json_decode($response);
if (json_last_error() == JSON_ERROR_NONE) {
// If valid dump.
echo $response;
} else {
echo json_encode(
['error' => $response]
);
}
exit;
}
/**
* Run main page.
*
* @return void
*/
public function run()
{
// Require specific CSS and JS.
ui_require_css_file('wizard');
ui_require_css_file('discovery');
ui_require_css_file('pen');
// Header section.
// Breadcrums.
$this->setBreadcrum([]);
$this->prepareBreadcrum(
[
[
'link' => '',
'label' => __('Configuration'),
'selected' => false,
],
[
'link' => '',
'label' => __('Templates'),
'selected' => false,
],
[
'link' => $this->baseUrl,
'label' => __('Private Enterprise Numbers'),
'selected' => true,
],
],
true
);
ui_print_page_header(
__('Private Enterprise Numbers'),
'',
false,
'',
true,
'',
false,
'',
GENERIC_SIZE_TEXT,
'',
$this->printHeader(true)
);
// Definition for AJAX.
html_print_input_hidden(
'ajax_file',
ui_get_full_url('ajax.php', false, false, false)
);
// Ajax page (hidden).
html_print_input_hidden(
'ajax_page',
$this->ajaxController
);
// Allow message area.
html_print_div(['id' => 'message_show_area']);
// Prints the main table.
html_print_div(
[
'id' => 'main_table_area',
'content' => $this->createMainTable(),
]
);
}
/**
* Load modal information for PEN management.
*
* Ajax. Direct HTML.
*
* @return void
*/
public function loadModal()
{
$values = [];
$id = (int) get_parameter('pen', 0);
if ($id > 0) {
$values = $this->getAll(
// Fields.
['*'],
// Filter.
['pen' => $id]
);
if (is_array($values)) {
$values = $values[0];
}
}
$form = [
'action' => '#',
'id' => 'modal_form',
'onsubmit' => 'return false;',
'class' => '',
];
$inputs = [];
$arguments = [
'name' => 'pen',
'type' => 'number',
'value' => $values['pen'],
'required' => true,
'return' => true,
'size' => 50,
];
if ((bool) $values['pen']) {
$arguments['disabled'] = true;
}
$inputs[] = [
'label' => __('PEN'),
'class' => 'flex-row',
'id' => 'div-pen',
'arguments' => $arguments,
];
$inputs[] = [
'label' => __('Manufacturer'),
'class' => 'flex-row',
'arguments' => [
'name' => 'manufacturer',
'id' => 'manufacturer',
'type' => 'text',
'required' => true,
'value' => io_safe_output($values['manufacturer']),
'return' => true,
],
];
$inputs[] = [
'label' => __('Description'),
'class' => 'flex-row',
'arguments' => [
'name' => 'description',
'id' => 'description',
'type' => 'textarea',
'value' => io_safe_output($values['description']),
'return' => true,
'rows' => 50,
'columns' => 30,
],
];
echo '<div id="div-form">';
echo parent::printForm(
[
'form' => $form,
'inputs' => $inputs,
],
true
);
echo '</div>';
}
/**
* Delete a manufacturer register from db.
*
* @return void
*/
public function delete()
{
$pen = get_parameter('pen', 0);
if (empty($pen)) {
echo json_encode(['error' => __('PEN is required')]);
} else {
if (db_process_sql_delete('tpen', ['pen' => $pen]) !== false) {
echo json_encode(['result' => __('Successfully deleted')]);
} else {
global $config;
echo json_encode(['error' => $config['dbconnection']->error]);
}
}
}
/**
* Add or update a manufacturer to private enterprise numbers.
*
* @return void
*/
public function add()
{
$pen = get_parameter('pen', 0);
$manufacturer = get_parameter('manufacturer', '');
$description = get_parameter('description', '');
$is_new = (bool) get_parameter('is_new', false);
if (empty($pen)) {
$error = __('PEN is required.');
}
if (empty($manufacturer)) {
$error = __('Manufacturer is required');
}
if (!empty($error)) {
echo json_encode(
['error' => $error]
);
}
// Add if not exists.
$current = $this->getAll(['pen'], ['pen' => $pen]);
if ($current === false) {
// New.
if ($is_new === false) {
echo json_encode(
[
'error' => __('This PEN definition does not exist'),
]
);
exit;
}
$rs = db_process_sql_insert(
'tpen',
[
'pen' => $pen,
'manufacturer' => $manufacturer,
'description' => $description,
]
);
$str = __('created');
} else {
// Update.
if ($is_new === true) {
echo json_encode(
[
'error' => __('This PEN definition already exists'),
]
);
exit;
}
$rs = db_process_sql_update(
'tpen',
[
'manufacturer' => $manufacturer,
'description' => $description,
],
['pen' => $pen]
);
$str = __('updated');
}
if ($rs === false) {
global $config;
echo json_encode(['error' => $config['dbconnection']->error]);
} else {
echo json_encode(['result' => __('Succesfully %s', $str)]);
}
}
/**
* Create the main table with the PENs info
*
* @return string Return entire the table
*/
public function createMainTable()
{
global $config;
$output = '';
// Datatables list.
try {
$columns = [
'pen',
'manufacturer',
'description',
'options',
];
$column_names = [
__('PEN'),
__('Manufacturer'),
__('Description'),
[
'text' => __('Options'),
'class' => 'action_buttons',
],
];
$this->tableId = 'keystore';
// Load datatables user interface.
$output .= ui_print_datatable(
[
'id' => $this->tableId,
'return' => true,
'class' => 'info_table',
'style' => 'width: 100%',
'columns' => $columns,
'column_names' => $column_names,
'ajax_url' => $this->ajaxController,
'ajax_data' => ['method' => 'draw'],
'no_sortable_columns' => [-1],
'order' => [
'field' => 'pen',
'direction' => 'asc',
],
'search_button_class' => 'sub filter float-right',
'form' => [
'inputs' => [
[
'label' => __('Free search'),
'type' => 'text',
'class' => 'mw250px',
'id' => 'free_search',
'name' => 'free_search',
],
],
],
]
);
} catch (Exception $e) {
echo $e->getMessage();
}
// Auxiliar div.
$output .= '<div id="modal" style="display: none"></div>';
$output .= '<div id="msg" style="display: none"></div>';
$output .= '<div id="aux" style="display: none"></div>';
// Create button.
$output .= parent::printInput(
[
'type' => 'submit',
'name' => 'create',
'label' => __('Register manufacturer'),
'attributes' => 'class="sub next"',
'return' => true,
]
);
ob_start();
?>
<script type="text/javascript">
function cleanupDOM() {
$("#div-form").empty();
}
function deletePEN(id) {
confirmDialog({
title: "<?php echo __('Are you sure?'); ?>",
message: "<?php echo __('Are you sure you want to delete this PEN?'); ?>",
ok: "<?php echo __('OK'); ?>",
cancel: "<?php echo __('Cancel'); ?>",
onAccept: function() {
$.ajax({
method: "post",
url: "<?php echo ui_get_full_url('ajax.php', false, false, false); ?>",
data: {
page: "<?php echo $this->ajaxController; ?>",
method: "delete",
pen: id
},
datatype: "json",
success: function(data) {
showMsg(data);
},
error: function(e) {
showMsg(e);
}
});
}
});
}
function showForm(id) {
var btn_ok_text = "<?php echo __('OK'); ?>";
var btn_cancel_text = "<?php echo __('Cancel'); ?>";
var title = "<?php echo __('Register new manufacturer'); ?>";
var is_new = 1;
if (id) {
btn_ok_text = "<?php echo __('Update'); ?>";
title = "<?php echo __('Update'); ?> " + id;
is_new = 0;
}
load_modal({
target: $("#modal"),
form: "modal_form",
url: "<?php echo ui_get_full_url('ajax.php', false, false, false); ?>",
ajax_callback: showMsg,
cleanup: cleanupDOM,
modal: {
title: title,
ok: btn_ok_text,
cancel: btn_cancel_text
},
extradata: [
{
name: "pen",
value: id
},
{
name: 'is_new',
value: is_new
}
],
onshow: {
page: "<?php echo $this->ajaxController; ?>",
method: "loadModal"
},
onsubmit: {
page: "<?php echo $this->ajaxController; ?>",
method: "add"
}
});
}
/**
* Process ajax responses and shows a dialog with results.
*/
function showMsg(data) {
var title = "<?php echo __('Success'); ?>";
var text = "";
var failed = 0;
try {
data = JSON.parse(data);
text = data["result"];
} catch (err) {
title = "<?php echo __('Failed'); ?>";
text = err.message;
failed = 1;
}
if (!failed && data["error"] != undefined) {
title = "<?php echo __('Failed'); ?>";
text = data["error"];
failed = 1;
}
if (data["report"] != undefined) {
data["report"].forEach(function(item) {
text += "<br>" + item;
});
}
$("#msg").empty();
$("#msg").html(text);
$("#msg").dialog({
width: 450,
position: {
my: "center",
at: "center",
of: window,
collision: "fit"
},
title: title,
buttons: [
{
class:
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
text: "OK",
click: function(e) {
if (!failed) {
$(".ui-dialog-content").dialog("close");
$(".info").hide();
cleanupDOM();
dt_keystore.draw(false);
} else {
$(this).dialog("close");
}
}
}
]
});
}
$(document).ready(function() {
$("#submit-create").click(function() {
showForm();
});
});
</script>
<?php
$output .= ob_get_clean();
return $output;
}
}

View File

@ -443,6 +443,8 @@ class CredentialStore extends Wizard
*/ */
public function draw() public function draw()
{ {
global $config;
// Datatables offset, limit and order. // Datatables offset, limit and order.
$filter = get_parameter('filter', []); $filter = get_parameter('filter', []);
$start = get_parameter('start', 0); $start = get_parameter('start', 0);

View File

@ -38,7 +38,7 @@ class HTML
/** /**
* Breadcrum * Breadcrum
* *
* @var array. * @var array
*/ */
public $breadcrum; public $breadcrum;
@ -119,7 +119,7 @@ class HTML
/** /**
* Add an element to breadcrum array. * Add an element to breadcrum array.
* *
* @param string $breads Elements to add to breadcrum. * @param array $breads Elements to add to breadcrum.
* *
* @return void * @return void
*/ */
@ -335,6 +335,27 @@ class HTML
} }
/**
* Return formatted html for error handler.
*
* @param string $message Error mesage.
*
* @return string
*/
public function error($message)
{
if (is_ajax()) {
echo json_encode(
[
'error' => ui_print_error_message($message, '', true),
]
);
} else {
return ui_print_error_message($message, '', true);
}
}
/** /**
* Print input using functions html lib. * Print input using functions html lib.
* *
@ -725,6 +746,7 @@ class HTML
) { ) {
$form = $data['form']; $form = $data['form'];
$inputs = $data['inputs']; $inputs = $data['inputs'];
$rawInputs = $data['rawInputs'];
$js = $data['js']; $js = $data['js'];
$rawjs = $data['js_block']; $rawjs = $data['js_block'];
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
@ -767,6 +789,11 @@ class HTML
$output .= '</ul>'; $output .= '</ul>';
// There is possible add raw inputs for this form.
if (empty($rawInputs) === false) {
$output .= $rawInputs;
}
if ($print_white_box === true) { if ($print_white_box === true) {
$output .= '</div>'; $output .= '</div>';
} }
@ -800,7 +827,7 @@ class HTML
$form = $data['form']; $form = $data['form'];
$rows = $data['rows']; $rows = $data['rows'];
$rawInputs = $data['rawInputs'];
$js = $data['js']; $js = $data['js'];
$rawjs = $data['js_block']; $rawjs = $data['js_block'];
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
@ -875,6 +902,11 @@ class HTML
} }
} }
// There is possible add raw inputs for this form.
if (empty($rawInputs) === false) {
$output .= $rawInputs;
}
$output .= '</div>'; $output .= '</div>';
$output .= '<ul class="wizard">'.$output_submit.'</ul>'; $output .= '<ul class="wizard">'.$output_submit.'</ul>';
@ -905,6 +937,7 @@ class HTML
{ {
$form = $data['form']; $form = $data['form'];
$inputs = $data['inputs']; $inputs = $data['inputs'];
$rawInputs = $data['rawInputs'];
$js = $data['js']; $js = $data['js'];
$rawjs = $data['js_block']; $rawjs = $data['js_block'];
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
@ -940,7 +973,13 @@ class HTML
} }
$output .= '</ul>'; $output .= '</ul>';
// There is possible add raw inputs for this form.
if (empty($rawInputs) === false) {
$output .= $rawInputs;
}
$output .= '</div>'; $output .= '</div>';
$output .= '<ul class="wizard">'.$output_submit.'</ul>'; $output .= '<ul class="wizard">'.$output_submit.'</ul>';
$output .= '</form>'; $output .= '</form>';
$output .= '<script>'.$js.'</script>'; $output .= '<script>'.$js.'</script>';
@ -1000,4 +1039,72 @@ class HTML
} }
/**
* Returns a n-dimensional array (data) into a html tree structure.
*
* Advanced documentation:
* https://www.jqueryscript.net/other/Checkable-Hierarchical-Tree.html
*
* @param string $target Target DOM id.
* @param array $data N-dimensional array.
* @param string $onclick Onclick function.
* @param string $onchange Onchange function.
*
* @return string
*/
public static function printTree(
$target,
$data,
$onclick='',
$onchange=''
) {
ui_require_css_file('simTree');
ui_require_javascript_file('simTree');
/*
* SAMPLE SELECT ALL.
*
* echo '<div class="subtitle">';
* echo '<span>';
* echo __('Please select devices to be monitored');
* echo '</span><div class="manage">';
* echo '<button onclick="$(\'.sim-tree li a\').each(function(){simTree_tree.doCheck($(this), false); simTree_tree.clickNode($(this));});">';
* echo __('select all');
* echo '</button>';
* echo '<button onclick="$(\'.sim-tree li a\').each(function(){simTree_tree.doCheck($(this), true); simTree_tree.clickNode($(this));});">';
* echo __('deselect all');
* echo '</button>';
* echo '</div>';
* echo '</div>';
*
* END SAMPLE SELECT ALL.
*/
$output = '
<script type="text/javascript">
var simTree_'.$target.';
$(document).ready(function() {
simTree_'.$target.' = simTree({
el: $('.$target.'),
data: '.json_encode($data).',
onClick: function (item) {'.$onclick.';},
onChange: function (item) {
'.$onchange.';
$("#tree-data-'.$target.'").val(JSON.stringify(this.sels));
},
check: true,
linkParent: true
});
$("#'.$target.'").append(
\'<input type="hidden" id="tree-data-'.$target.'" name="tree-data-'.$target.'">\'
);
$("#tree-data-'.$target.'").val(JSON.stringify(simTree_'.$target.'.sels));
});
</script>';
return $output;
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -20,7 +20,7 @@
/** /**
* Pandora build version and version * Pandora build version and version
*/ */
$build_version = 'PC200413'; $build_version = 'PC200414';
$pandora_version = 'v7.0NG.744'; $pandora_version = 'v7.0NG.744';
// Do not overwrite default timezone set if defined. // Do not overwrite default timezone set if defined.

View File

@ -524,9 +524,15 @@ define('ARROW_TYPE', 1);
// Discovery task steps. // Discovery task steps.
define('STEP_SCANNING', 1); define('STEP_SCANNING', 1);
define('STEP_CAPABILITIES', 7);
define('STEP_AFT', 2); define('STEP_AFT', 2);
define('STEP_TRACEROUTE', 3); define('STEP_TRACEROUTE', 3);
define('STEP_GATEWAY', 4); define('STEP_GATEWAY', 4);
define('STEP_MONITORING', 5);
define('STEP_PROCESSING', 6);
define('STEP_STATISTICS', 1);
define('STEP_APP_SCAN', 2);
define('STEP_CUSTOM_QUERIES', 3);
// Networkmap node types. // Networkmap node types.
define('NODE_AGENT', 0); define('NODE_AGENT', 0);
@ -594,6 +600,11 @@ define('DISCOVERY_DEPLOY_AGENTS', 9);
define('DISCOVERY_APP_SAP', 10); define('DISCOVERY_APP_SAP', 10);
// Force task build tmp results.
define('DISCOVERY_REVIEW', 0);
define('DISCOVERY_STANDARD', 1);
define('DISCOVERY_RESULTS', 2);
// Discovery types matching definition. // Discovery types matching definition.
define('DISCOVERY_SCRIPT_HOSTDEVICES_CUSTOM', 0); define('DISCOVERY_SCRIPT_HOSTDEVICES_CUSTOM', 0);
// Standard applications. // Standard applications.

View File

@ -2439,7 +2439,13 @@ function graphic_agentaccess(
if ($return === true) { if ($return === true) {
return vbar_graph($data_array, $options, 1); return vbar_graph($data_array, $options, 1);
} else { } else {
echo vbar_graph($data_array, $options, 1); $options['generals']['pdf']['width'] = 350;
$options['generals']['pdf']['height'] = 125;
$imgbase64 = '<img src="data:image/jpg;base64,';
$imgbase64 .= vbar_graph($data_array, $options, 2);
$imgbase64 .= '" />';
return $imgbase64;
} }
} }

View File

@ -722,6 +722,7 @@ function html_print_select(
* @param string $style The string of style. * @param string $style The string of style.
* @param mixed $size Max elements showed in select or default (size=10) * @param mixed $size Max elements showed in select or default (size=10)
* @param integer $truncante_size Truncate size of the element, by default is set to GENERIC_SIZE_TEXT constant * @param integer $truncante_size Truncate size of the element, by default is set to GENERIC_SIZE_TEXT constant
* @param integer $class Class to apply.
* *
* @return string HTML code if return parameter is true. * @return string HTML code if return parameter is true.
*/ */
@ -738,7 +739,8 @@ function html_print_select_from_sql(
$disabled=false, $disabled=false,
$style=false, $style=false,
$size=false, $size=false,
$trucate_size=GENERIC_SIZE_TEXT $trucate_size=GENERIC_SIZE_TEXT,
$class=''
) { ) {
global $config; global $config;
@ -770,7 +772,7 @@ function html_print_select_from_sql(
$return, $return,
$multiple, $multiple,
$sort, $sort,
'', $class,
$disabled, $disabled,
$style, $style,
'', '',
@ -1087,7 +1089,7 @@ function html_print_extended_select_for_time(
ob_start(); ob_start();
// Use the no_meta parameter because this image is only in the base console // Use the no_meta parameter because this image is only in the base console
echo '<div id="'.$uniq_name.'_default" style="width:100%;display:inline;">'; echo '<div id="'.$uniq_name.'_default" style="width:100%;display:flex;align-items: baseline;">';
html_print_select( html_print_select(
$fields, $fields,
$uniq_name.'_select', $uniq_name.'_select',
@ -1121,7 +1123,7 @@ function html_print_extended_select_for_time(
echo '</div>'; echo '</div>';
echo '<div id="'.$uniq_name.'_manual" style="width:100%;display:inline;">'; echo '<div id="'.$uniq_name.'_manual" style="width:100%;display:flex;">';
html_print_input_text($uniq_name.'_text', $selected, '', $size, 255, false, $readonly, false, '', $class); html_print_input_text($uniq_name.'_text', $selected, '', $size, 255, false, $readonly, false, '', $class);
html_print_input_hidden($name, $selected, false, $uniq_name); html_print_input_hidden($name, $selected, false, $uniq_name);
@ -1159,8 +1161,8 @@ function html_print_extended_select_for_time(
$('#text-".$uniq_name."_text').val(seconds); $('#text-".$uniq_name."_text').val(seconds);
adjustTextUnits('".$uniq_name."'); adjustTextUnits('".$uniq_name."');
calculateSeconds('".$uniq_name."'); calculateSeconds('".$uniq_name."');
$('#".$uniq_name."_manual').show(); $('#".$uniq_name."_manual').css('display', 'flex');
$('#".$uniq_name."_default').hide(); $('#".$uniq_name."_default').css('display', 'none');
} }
</script>"; </script>";
$returnString = ob_get_clean(); $returnString = ob_get_clean();
@ -1334,6 +1336,7 @@ function html_print_input_text_extended(
'onkeyup', 'onkeyup',
'required', 'required',
'autocomplete', 'autocomplete',
'form',
]; ];
$output = '<input '.($password ? 'type="password" autocomplete="'.$autocomplete.'" ' : 'type="text" '); $output = '<input '.($password ? 'type="password" autocomplete="'.$autocomplete.'" ' : 'type="text" ');
@ -1550,7 +1553,9 @@ function html_print_input_text(
$class='', $class='',
$onChange='', $onChange='',
$autocomplete='', $autocomplete='',
$autofocus=false $autofocus=false,
$onKeyDown='',
$formTo=''
) { ) {
if ($maxlength == 0) { if ($maxlength == 0) {
$maxlength = 255; $maxlength = 255;
@ -1575,6 +1580,10 @@ function html_print_input_text(
$attr['onchange'] = $onChange; $attr['onchange'] = $onChange;
} }
if ($onKeyDown != '') {
$attr['onkeydown'] = $onKeyDown;
}
if ($autocomplete !== '') { if ($autocomplete !== '') {
$attr['autocomplete'] = $autocomplete; $attr['autocomplete'] = $autocomplete;
} }
@ -1583,6 +1592,10 @@ function html_print_input_text(
$attr['autofocus'] = $autofocus; $attr['autofocus'] = $autofocus;
} }
if ($formTo != '') {
$attr['form'] = $formTo;
}
return html_print_input_text_extended( return html_print_input_text_extended(
$name, $name,
$value, $value,
@ -3457,7 +3470,10 @@ function html_print_input($data, $wrapper='div', $input_only=false)
((isset($data['function']) === true) ? $data['function'] : ''), ((isset($data['function']) === true) ? $data['function'] : ''),
((isset($data['class']) === true) ? $data['class'] : ''), ((isset($data['class']) === true) ? $data['class'] : ''),
((isset($data['onChange']) === true) ? $data['onChange'] : ''), ((isset($data['onChange']) === true) ? $data['onChange'] : ''),
((isset($data['autocomplete']) === true) ? $data['autocomplete'] : '') ((isset($data['autocomplete']) === true) ? $data['autocomplete'] : ''),
false,
((isset($data['onKeyDown']) === true) ? $data['onKeyDown'] : ''),
((isset($data['form']) === true) ? $data['form'] : '')
); );
break; break;
@ -3504,24 +3520,6 @@ function html_print_input($data, $wrapper='div', $input_only=false)
); );
break; break;
case 'text':
$output .= html_print_input_text(
$data['name'],
$data['value'],
((isset($data['alt']) === true) ? $data['alt'] : ''),
((isset($data['size']) === true) ? $data['size'] : 50),
((isset($data['maxlength']) === true) ? $data['maxlength'] : 255),
((isset($data['return']) === true) ? $data['return'] : false),
((isset($data['disabled']) === true) ? $data['disabled'] : false),
((isset($data['required']) === true) ? $data['required'] : false),
((isset($data['function']) === true) ? $data['function'] : ''),
((isset($data['class']) === true) ? $data['class'] : ''),
((isset($data['onChange']) === true) ? $data['onChange'] : ''),
((isset($data['autocomplete']) === true) ? $data['autocomplete'] : ''),
((isset($data['autofocus']) === true) ? $data['autofocus'] : false)
);
break;
case 'email': case 'email':
$output .= html_print_input_email($data); $output .= html_print_input_email($data);
break; break;
@ -3604,7 +3602,8 @@ function html_print_input($data, $wrapper='div', $input_only=false)
((isset($data['disabled']) === true) ? $data['disabled'] : false), ((isset($data['disabled']) === true) ? $data['disabled'] : false),
((isset($data['style']) === true) ? $data['style'] : false), ((isset($data['style']) === true) ? $data['style'] : false),
((isset($data['size']) === true) ? $data['size'] : false), ((isset($data['size']) === true) ? $data['size'] : false),
((isset($data['trucate_size']) === true) ? $data['trucate_size'] : GENERIC_SIZE_TEXT) ((isset($data['trucate_size']) === true) ? $data['trucate_size'] : GENERIC_SIZE_TEXT),
((isset($data['class']) === true) ? $data['class'] : '')
); );
break; break;

View File

@ -783,7 +783,7 @@ function snmp_browser_print_container($return=false, $width='100%', $height='60%
$table2->cellstyle[0][2] = 'text-align:center;'; $table2->cellstyle[0][2] = 'text-align:center;';
// This extra div that can be handled by jquery's dialog. // This extra div that can be handled by jquery's dialog.
$output = '<div id="snmp_browser_container" style="display:'.$display.'">'; $output = '<div id="snmp_browser_container" style="'.$display.'">';
$output .= '<div style="text-align: left; width: '.$width.'; height: '.$height.';">'; $output .= '<div style="text-align: left; width: '.$width.'; height: '.$height.';">';
$output .= '<div style="width: 100%">'; $output .= '<div style="width: 100%">';
$output .= html_print_table($table, true); $output .= html_print_table($table, true);

View File

@ -123,11 +123,11 @@ function treeview_printModuleTable($id_module, $server_data=false, $no_head=fals
$row['data'] = $module_group; $row['data'] = $module_group;
$table->data['module_group'] = $row; $table->data['module_group'] = $row;
// Description // Description.
$row = []; $row = [];
$row['title'] = __('Description'); $row['title'] = __('Description');
$row['data'] = ui_print_truncate_text( $row['data'] = ui_print_truncate_text(
$module['descripcion'];, $module['descripcion'],
'description', 'description',
true, true,
true, true,
@ -761,21 +761,25 @@ function treeview_printTable($id_agente, $server_data=[], $no_head=false)
} }
} }
// End of table advanced // End of table advanced.
$table_advanced = html_print_table($table, true); $table_advanced = html_print_table($table, true);
$table_advanced .= '<br>'; $table_advanced .= '<br>';
ui_toggle($table_advanced, __('Advanced information')); ui_toggle($table_advanced, __('Advanced information'));
if ($config['agentaccess']) { if ($config['agentaccess']) {
$access_graph = '<div style="width:100%; height:130px;">'; $access_graph = '<div style="width:100%; height:130px; text-align:center;">';
$access_graph .= graphic_agentaccess( $access_graph .= graphic_agentaccess(
$id_agente, $id_agente,
SECONDS_1DAY, SECONDS_1DAY,
true false
); );
$access_graph .= '</div>'; $access_graph .= '</div>';
ui_toggle($access_graph, __('Agent access rate (24h)'));
ui_toggle(
$access_graph,
__('Agent access rate (24h)')
);
} }
$events_graph = '<div style="width: 100%; height: 90px; display: flex; flex-direction: row; justify-content: center;">'; $events_graph = '<div style="width: 100%; height: 90px; display: flex; flex-direction: row; justify-content: center;">';

View File

@ -2848,6 +2848,7 @@ function ui_print_status_sets(
* [ * [
* 'page' => 'operation/agentes/ver_agente', Target page. * 'page' => 'operation/agentes/ver_agente', Target page.
* 'interval' => 100 / $agent["intervalo"], Ask every interval seconds. * 'interval' => 100 / $agent["intervalo"], Ask every interval seconds.
* 'simple' => 0,
* 'data' => [ Data to be sent to target page. * 'data' => [ Data to be sent to target page.
* 'id_agente' => $id_agente, * 'id_agente' => $id_agente,
* 'refresh_contact' => 1, * 'refresh_contact' => 1,
@ -2881,56 +2882,99 @@ function ui_progress(
$text = $progress.'%'; $text = $progress.'%';
} }
$id = uniqid();
ui_require_css_file('progress'); ui_require_css_file('progress');
$output .= '<span class="progress_main" data-label="'.$text; $output .= '<span id="'.$id.'" class="progress_main" data-label="'.$text;
$output .= '" style="width: '.$width.'; height: '.$height.'em; border: 1px solid '.$color.'">'; $output .= '" style="width: '.$width.'; height: '.$height.'em; border: 1px solid '.$color.'">';
$output .= '<span class="progress" style="width: '.$progress.'%; background: '.$color.'"></span>'; $output .= '<span id="'.$id.'_progress" class="progress" style="width: '.$progress.'%; background: '.$color.'"></span>';
$output .= '</span>'; $output .= '</span>';
if ($ajax !== false && is_array($ajax)) { if ($ajax !== false && is_array($ajax)) {
$output .= '<script type="text/javascript"> if ($ajax['simple']) {
$output .= '<script type="text/javascript">
$(document).ready(function() { $(document).ready(function() {
setInterval(() => { setInterval(() => {
last = $(".progress_main").attr("data-label").split(" ")[0]*1; $.post({
width = $(".progress").width() / $(".progress").parent().width() * 100; url: "'.ui_get_full_url('ajax.php', false, false, false).'",
data: {';
if (is_array($ajax['data'])) {
foreach ($ajax['data'] as $token => $value) {
$output .= '
'.$token.':"'.$value.'",';
}
}
$output .= '
page: "'.$ajax['page'].'"
},
success: function(data) {
try {
val = JSON.parse(data);
$("#'.$id.'").attr("data-label", val + " %");
$("#'.$id.'_progress").width(val+"%");';
if (isset($ajax['oncomplete'])) {
$output .= '
if (val == 100) {
'.$ajax['oncomplete'].'($("#'.$id.'"));
}
';
}
$output .= '
} catch (e) {
console.error(e);
}
}
});
}, '.($ajax['interval'] > 0 ? $ajax['interval'] * 1000 : 30000 ).');
});
</script>';
} else {
$output .= '<script type="text/javascript">
$(document).ready(function() {
setInterval(() => {
last = $("#'.$id.'").attr("data-label").split(" ")[0]*1;
width = $("#'.$id.'_progress").width() / $("#'.$id.'_progress").parent().width() * 100;
width_interval = '.$ajax['interval'].'; width_interval = '.$ajax['interval'].';
if (last % 10 == 0) { if (last % 10 == 0) {
$.post({ $.post({
url: "'.ui_get_full_url('ajax.php', false, false, false).'", url: "'.ui_get_full_url('ajax.php', false, false, false).'",
data: {'; data: {';
if (is_array($ajax['data'])) { if (is_array($ajax['data'])) {
foreach ($ajax['data'] as $token => $value) { foreach ($ajax['data'] as $token => $value) {
$output .= ' $output .= '
'.$token.':"'.$value.'",'; '.$token.':"'.$value.'",';
}
} }
}
$output .= ' $output .= '
page: "'.$ajax['page'].'" page: "'.$ajax['page'].'"
}, },
success: function(data) { success: function(data) {
try { try {
val = JSON.parse(data); val = JSON.parse(data);
$(".progress_main").attr("data-label", val["last_contact"]+" s"); $("#'.$id.'").attr("data-label", val["last_contact"]+" s");
$(".progress").width(val["progress"]+"%"); $("#'.$id.'_progress").width(val["progress"]+"%");
} catch (e) { } catch (e) {
console.error(e); console.error(e);
$(".progress_text").attr("data-label", (last -1) + " s"); $(".progress_text").attr("data-label", (last -1) + " s");
if (width < 100) { if (width < 100) {
$(".progress").width((width+width_interval) + "%"); $("#'.$id.'_progress").width((width+width_interval) + "%");
} }
} }
} }
}); });
} else { } else {
$(".progress_main").attr("data-label", (last -1) + " s"); $("#'.$id.'").attr("data-label", (last -1) + " s");
if (width < 100) { if (width < 100) {
$(".progress").width((width+width_interval) + "%"); $("#'.$id.'_progress").width((width+width_interval) + "%");
} }
} }
}, 1000); }, 1000);
}); });
</script>'; </script>';
}
} }
if (!$return) { if (!$return) {
@ -3469,10 +3513,13 @@ function ui_print_datatable(array $parameters)
ui_require_javascript_file('buttons.html5.min'); ui_require_javascript_file('buttons.html5.min');
ui_require_javascript_file('buttons.print.min'); ui_require_javascript_file('buttons.print.min');
$output = $include.$output; if (isset($parameters['return']) && $parameters['return'] == true) {
// Compat.
$parameters['print'] = false;
}
// Print datatable if needed. // Print datatable if needed.
if (isset($parameters['print']) === false || $parameters['print'] === false) { if (isset($parameters['print']) === false || $parameters['print'] === true) {
echo $output; echo $output;
} }
@ -3673,8 +3720,8 @@ function ui_toggle(
// Generate unique Id. // Generate unique Id.
$uniqid = uniqid(''); $uniqid = uniqid('');
$image_a = html_print_image($img_a, true, false, true); $image_a = html_print_image($img_a, true, [ 'style' => 'object-fit: contain;' ], true);
$image_b = html_print_image($img_b, true, false, true); $image_b = html_print_image($img_b, true, [ 'style' => 'object-fit: contain;' ], true);
// Options. // Options.
if ($hidden_default) { if ($hidden_default) {
$style = 'display:none'; $style = 'display:none';
@ -3698,6 +3745,7 @@ function ui_toggle(
$original, $original,
true, true,
[ [
'style' => 'object-fit: contain;',
'title' => $title, 'title' => $title,
'id' => 'image_'.$uniqid, 'id' => 'image_'.$uniqid,
] ]

View File

@ -0,0 +1,2 @@
// http://code.accursoft.com/caret - 1.3.3
!function(e){e.fn.caret=function(e){var t=this[0],n="true"===t.contentEditable;if(0==arguments.length){if(window.getSelection){if(n){t.focus();var o=window.getSelection().getRangeAt(0),r=o.cloneRange();return r.selectNodeContents(t),r.setEnd(o.endContainer,o.endOffset),r.toString().length}return t.selectionStart}if(document.selection){if(t.focus(),n){var o=document.selection.createRange(),r=document.body.createTextRange();return r.moveToElementText(t),r.setEndPoint("EndToEnd",o),r.text.length}var e=0,c=t.createTextRange(),r=document.selection.createRange().duplicate(),a=r.getBookmark();for(c.moveToBookmark(a);0!==c.moveStart("character",-1);)e++;return e}return t.selectionStart?t.selectionStart:0}if(-1==e&&(e=this[n?"text":"val"]().length),window.getSelection)n?(t.focus(),window.getSelection().collapse(t.firstChild,e)):t.setSelectionRange(e,e);else if(document.body.createTextRange)if(n){var c=document.body.createTextRange();c.moveToElementText(t),c.moveStart("character",e),c.collapse(!0),c.select()}else{var c=t.createTextRange();c.move("character",e),c.select()}return n||t.focus(),e}}(jQuery);

View File

@ -0,0 +1,370 @@
/*
jQuery tagEditor v1.0.21
Copyright (c) 2014 Simon Steinberger / Pixabay
GitHub: https://github.com/Pixabay/jQuery-tagEditor
License: http://www.opensource.org/licenses/mit-license.php
*/
(function($){
// auto grow input (stackoverflow.com/questions/931207)
$.fn.tagEditorInput=function(){var t=" ",e=$(this),n=parseInt(e.css("fontSize")),i=$("<span/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:e.css("fontSize"),fontFamily:e.css("fontFamily"),fontWeight:e.css("fontWeight"),letterSpacing:e.css("letterSpacing"),whiteSpace:"nowrap"}),s=function(){if(t!==(t=e.val())){i.text(t);var s=i.width()+n;20>s&&(s=20),s!=e.width()&&e.width(s)}};return i.insertAfter(e),e.bind("keyup keydown focus",s)};
// plugin with val as parameter for public methods
$.fn.tagEditor = function(options, val, blur){
// helper
function escape(tag) {
return tag.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
// build options dictionary with default values
var blur_result, o = $.extend({}, $.fn.tagEditor.defaults, options), selector = this;
// store regex and default delimiter in options for later use
o.dregex = new RegExp('['+o.delimiter.replace('-', '\-')+']', 'g');
// public methods
if (typeof options == 'string') {
// depending on selector, response may contain tag lists of multiple editor instances
var response = [];
selector.each(function(){
// the editor is the next sibling to the hidden, original field
var el = $(this), o = el.data('options'), ed = el.next('.tag-editor');
if (options == 'getTags')
response.push({field: el[0], editor: ed, tags: ed.data('tags')});
else if (options == 'addTag') {
if (o.maxTags && ed.data('tags').length >= o.maxTags) return false;
// insert new tag
$('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>').appendTo(ed).find('.tag-editor-tag')
.html('<input type="text" maxlength="'+o.maxLength+'">').addClass('active').find('input').val(val).blur();
if (!blur) ed.click();
else $('.placeholder', ed).remove();
} else if (options == 'removeTag') {
// trigger delete on matching tag, then click editor to create a new tag
$('.tag-editor-tag', ed).filter(function(){return $(this).text()==val;}).closest('li').find('.tag-editor-delete').click();
if (!blur) ed.click();
} else if (options == 'destroy') {
el.removeClass('tag-editor-hidden-src').removeData('options').off('focus.tag-editor').next('.tag-editor').remove();
}
});
return options == 'getTags' ? response : this;
}
// delete selected tags on backspace, delete, ctrl+x
if (window.getSelection) $(document).off('keydown.tag-editor').on('keydown.tag-editor', function(e){
if (e.which == 8 || e.which == 46 || e.ctrlKey && e.which == 88) {
try {
var sel = getSelection(), el = document.activeElement.tagName != 'INPUT' ? $(sel.getRangeAt(0).startContainer.parentNode).closest('.tag-editor') : 0;
} catch(e){ el = 0; }
if (sel.rangeCount > 0 && el && el.length) {
var tags = [], splits = sel.toString().split(el.prev().data('options').dregex);
for (i=0; i<splits.length; i++){ var tag = $.trim(splits[i]); if (tag) tags.push(tag); }
$('.tag-editor-tag', el).each(function(){
if (~$.inArray($(this).text(), tags)) $(this).closest('li').find('.tag-editor-delete').click();
});
return false;
}
}
});
return selector.each(function(){
var el = $(this), tag_list = []; // cache current tags
// create editor (ed) instance
var ed = $('<ul '+(o.clickDelete ? 'oncontextmenu="return false;" ' : '')+'class="tag-editor"></ul>').insertAfter(el);
el.addClass('tag-editor-hidden-src') // hide original field
.data('options', o) // set data on hidden field
.on('focus.tag-editor', function(){ ed.click(); }); // simulate tabindex
// add dummy item for min-height on empty editor
ed.append('<li style="width:1px">&nbsp;</li>');
// markup for new tag
var new_tag = '<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>';
// helper: update global data
function set_placeholder(){
if (o.placeholder && !tag_list.length && !$('.deleted, .placeholder, input', ed).length)
ed.append('<li class="placeholder"><div>'+o.placeholder+'</div></li>');
}
// helper: update global data
function update_globals(init){
var old_tags = tag_list.toString();
tag_list = $('.tag-editor-tag:not(.deleted)', ed).map(function(i, e) {
var val = $.trim($(this).hasClass('active') ? $(this).find('input').val() : $(e).text());
if (val) return val;
}).get();
ed.data('tags', tag_list);
el.val(tag_list.join(o.delimiter[0]));
// change callback except for plugin init
if (!init) if (old_tags != tag_list.toString()) o.onChange(el, ed, tag_list);
set_placeholder();
}
ed.click(function(e, closest_tag){
var d, dist = 99999, loc;
// do not create tag when user selects tags by text selection
if (window.getSelection && getSelection() != '') return;
if (o.maxTags && ed.data('tags').length >= o.maxTags) { ed.find('input').blur(); return false; }
blur_result = true
$('input:focus', ed).blur();
if (!blur_result) return false;
blur_result = true
// always remove placeholder on click
$('.placeholder', ed).remove();
if (closest_tag && closest_tag.length)
loc = 'before';
else {
// calculate tag closest to click position
$('.tag-editor-tag', ed).each(function(){
var tag = $(this), to = tag.offset(), tag_x = to.left, tag_y = to.top;
if (e.pageY >= tag_y && e.pageY <= tag_y+tag.height()) {
if (e.pageX < tag_x) loc = 'before', d = tag_x - e.pageX;
else loc = 'after', d = e.pageX - tag_x - tag.width();
if (d < dist) dist = d, closest_tag = tag;
}
});
}
if (loc == 'before') {
$(new_tag).insertBefore(closest_tag.closest('li')).find('.tag-editor-tag').click();
} else if (loc == 'after')
$(new_tag).insertAfter(closest_tag.closest('li')).find('.tag-editor-tag').click();
else // empty editor
$(new_tag).appendTo(ed).find('.tag-editor-tag').click();
return false;
});
ed.on('click', '.tag-editor-delete', function(e){
// delete icon is hidden when input is visible; place cursor near invisible delete icon on click
if ($(this).prev().hasClass('active')) { $(this).closest('li').find('input').caret(-1); return false; }
var li = $(this).closest('li'), tag = li.find('.tag-editor-tag');
if (o.beforeTagDelete(el, ed, tag_list, tag.text()) === false) return false;
tag.addClass('deleted').animate({width: 0}, o.animateDelete, function(){ li.remove(); set_placeholder(); });
update_globals();
return false;
});
// delete on right mouse click or ctrl+click
if (o.clickDelete)
ed.on('mousedown', '.tag-editor-tag', function(e){
if (e.ctrlKey || e.which > 1) {
var li = $(this).closest('li'), tag = li.find('.tag-editor-tag');
if (o.beforeTagDelete(el, ed, tag_list, tag.text()) === false) return false;
tag.addClass('deleted').animate({width: 0}, o.animateDelete, function(){ li.remove(); set_placeholder(); });
update_globals();
return false;
}
});
ed.on('click', '.tag-editor-tag', function(e){
// delete on right click or ctrl+click -> exit
if (o.clickDelete && (e.ctrlKey || e.which > 1)) return false;
if (!$(this).hasClass('active')) {
var tag = $(this).text();
// guess cursor position in text input
var left_percent = Math.abs(($(this).offset().left - e.pageX)/$(this).width()), caret_pos = parseInt(tag.length*left_percent),
input = $(this).html('<input type="text" maxlength="'+o.maxLength+'" value="'+escape(tag)+'">').addClass('active').find('input');
input.data('old_tag', tag).tagEditorInput().focus().caret(caret_pos);
if (o.autocomplete) {
var aco = $.extend({}, o.autocomplete);
// extend user provided autocomplete select method
var ac_select = 'select' in aco ? o.autocomplete.select : '';
aco.select = function(e, ui){ if (ac_select) ac_select(e, ui); setTimeout(function(){
ed.trigger('click', [$('.active', ed).find('input').closest('li').next('li').find('.tag-editor-tag')]);
}, 20); };
input.autocomplete(aco);
}
}
return false;
});
// helper: split into multiple tags, e.g. after paste
function split_cleanup(input){
var li = input.closest('li'), sub_tags = input.val().replace(/ +/, ' ').split(o.dregex),
old_tag = input.data('old_tag'), old_tags = tag_list.slice(0), exceeded = false, cb_val; // copy tag_list
for (var i=0; i<sub_tags.length; i++) {
tag = $.trim(sub_tags[i]).slice(0, o.maxLength);
if (o.forceLowercase) tag = tag.toLowerCase();
cb_val = o.beforeTagSave(el, ed, old_tags, old_tag, tag);
tag = cb_val || tag;
if (cb_val === false || !tag) continue;
// remove duplicates
if (o.removeDuplicates && ~$.inArray(tag, old_tags))
$('.tag-editor-tag', ed).each(function(){ if ($(this).text() == tag) $(this).closest('li').remove(); });
old_tags.push(tag);
li.before('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+escape(tag)+'</div><div class="tag-editor-delete"><i></i></div></li>');
if (o.maxTags && old_tags.length >= o.maxTags) { exceeded = true; break; }
}
input.attr('maxlength', o.maxLength).removeData('old_tag').val('')
if (exceeded) input.blur(); else input.focus();
update_globals();
}
ed.on('blur', 'input', function(e){
e.stopPropagation();
var input = $(this), old_tag = input.data('old_tag'), tag = $.trim(input.val().replace(/ +/, ' ').replace(o.dregex, o.delimiter[0]));
if (!tag) {
if (old_tag && o.beforeTagDelete(el, ed, tag_list, old_tag) === false) {
input.val(old_tag).focus();
blur_result = false;
update_globals();
return;
}
try { input.closest('li').remove(); } catch(e){}
if (old_tag) update_globals();
}
else if (tag.indexOf(o.delimiter[0])>=0) { split_cleanup(input); return; }
else if (tag != old_tag) {
if (o.forceLowercase) tag = tag.toLowerCase();
cb_val = o.beforeTagSave(el, ed, tag_list, old_tag, tag);
tag = cb_val || tag;
if (cb_val === false) {
if (old_tag) {
input.val(old_tag).focus();
blur_result = false;
update_globals();
return;
}
try { input.closest('li').remove(); } catch(e){}
if (old_tag) update_globals();
}
// remove duplicates
else if (o.removeDuplicates)
$('.tag-editor-tag:not(.active)', ed).each(function(){ if ($(this).text() == tag) $(this).closest('li').remove(); });
}
input.parent().html(escape(tag)).removeClass('active');
if (tag != old_tag) update_globals();
set_placeholder();
});
var pasted_content;
ed.on('paste', 'input', function(e){
$(this).removeAttr('maxlength');
pasted_content = $(this);
setTimeout(function(){ split_cleanup(pasted_content); }, 30);
});
// keypress delimiter
var inp;
ed.on('keypress', 'input', function(e){
if (o.delimiter.indexOf(String.fromCharCode(e.which))>=0) {
inp = $(this);
setTimeout(function(){ split_cleanup(inp); }, 20);
}
});
ed.on('keydown', 'input', function(e){
var $t = $(this);
// left/up key + backspace key on empty field
if ((e.which == 37 || !o.autocomplete && e.which == 38) && !$t.caret() || e.which == 8 && !$t.val()) {
var prev_tag = $t.closest('li').prev('li').find('.tag-editor-tag');
if (prev_tag.length) prev_tag.click().find('input').caret(-1);
else if ($t.val() && !(o.maxTags && ed.data('tags').length >= o.maxTags)) $(new_tag).insertBefore($t.closest('li')).find('.tag-editor-tag').click();
return false;
}
// right/down key
else if ((e.which == 39 || !o.autocomplete && e.which == 40) && ($t.caret() == $t.val().length)) {
var next_tag = $t.closest('li').next('li').find('.tag-editor-tag');
if (next_tag.length) next_tag.click().find('input').caret(0);
else if ($t.val()) ed.click();
return false;
}
// tab key
else if (e.which == 9) {
// shift+tab
if (e.shiftKey) {
var prev_tag = $t.closest('li').prev('li').find('.tag-editor-tag');
if (prev_tag.length) prev_tag.click().find('input').caret(0);
else if ($t.val() && !(o.maxTags && ed.data('tags').length >= o.maxTags)) $(new_tag).insertBefore($t.closest('li')).find('.tag-editor-tag').click();
// allow tabbing to previous element
else {
el.attr('disabled', 'disabled');
setTimeout(function(){ el.removeAttr('disabled'); }, 30);
return;
}
return false;
// tab
} else {
var next_tag = $t.closest('li').next('li').find('.tag-editor-tag');
if (next_tag.length) next_tag.click().find('input').caret(0);
else if ($t.val()) ed.click();
else return; // allow tabbing to next element
return false;
}
}
// del key
else if (e.which == 46 && (!$.trim($t.val()) || ($t.caret() == $t.val().length))) {
var next_tag = $t.closest('li').next('li').find('.tag-editor-tag');
if (next_tag.length) next_tag.click().find('input').caret(0);
else if ($t.val()) ed.click();
return false;
}
// enter key
else if (e.which == 13) {
ed.trigger('click', [$t.closest('li').next('li').find('.tag-editor-tag')]);
// trigger blur if maxTags limit is reached
if (o.maxTags && ed.data('tags').length >= o.maxTags) ed.find('input').blur();
return false;
}
// pos1
else if (e.which == 36 && !$t.caret()) ed.find('.tag-editor-tag').first().click();
// end
else if (e.which == 35 && $t.caret() == $t.val().length) ed.find('.tag-editor-tag').last().click();
// esc
else if (e.which == 27) {
$t.val($t.data('old_tag') ? $t.data('old_tag') : '').blur();
return false;
}
});
// create initial tags
var tags = o.initialTags.length ? o.initialTags : el.val().split(o.dregex);
for (var i=0; i<tags.length; i++) {
if (o.maxTags && i >= o.maxTags) break;
var tag = $.trim(tags[i].replace(/ +/, ' '));
if (tag) {
if (o.forceLowercase) tag = tag.toLowerCase();
tag_list.push(tag);
ed.append('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+escape(tag)+'</div><div class="tag-editor-delete"><i></i></div></li>');
}
}
update_globals(true); // true -> no onChange callback
// init sortable
if (o.sortable && $.fn.sortable) ed.sortable({
distance: 5, cancel: '.tag-editor-spacer, input', helper: 'clone',
update: function(){ update_globals(); }
});
});
};
$.fn.tagEditor.defaults = {
initialTags: [],
maxTags: 0,
maxLength: 50,
delimiter: ',;',
placeholder: '',
forceLowercase: true,
removeDuplicates: true,
clickDelete: false,
animateDelete: 175,
sortable: true, // jQuery UI sortable
autocomplete: null, // options dict for jQuery UI autocomplete
// callbacks
onChange: function(){},
beforeTagSave: function(){},
beforeTagDelete: function(){}
};
}(jQuery));

File diff suppressed because one or more lines are too long

View File

@ -837,8 +837,8 @@ function post_process_select_events(name) {
*/ */
function period_select_init(name, allow_zero) { function period_select_init(name, allow_zero) {
// Manual mode is hidden by default // Manual mode is hidden by default
$("#" + name + "_manual").hide(); $("#" + name + "_manual").css("display", "none");
$("#" + name + "_default").show(); $("#" + name + "_default").css("display", "flex");
// If the text input is empty, we put on it 5 minutes by default // If the text input is empty, we put on it 5 minutes by default
if ($("#text-" + name + "_text").val() == "") { if ($("#text-" + name + "_text").val() == "") {
@ -852,8 +852,8 @@ function period_select_init(name, allow_zero) {
} }
} else if ($("#text-" + name + "_text").val() == 0 && allow_zero != true) { } else if ($("#text-" + name + "_text").val() == 0 && allow_zero != true) {
$("#" + name + "_units option:last").prop("selected", false); $("#" + name + "_units option:last").prop("selected", false);
$("#" + name + "_manual").show(); $("#" + name + "_manual").css("display", "flex");
$("#" + name + "_default").hide(); $("#" + name + "_default").css("display", "none");
} }
} }
@ -941,13 +941,13 @@ function selectFirst(name) {
*/ */
function toggleBoth(name) { function toggleBoth(name) {
if ($("#" + name + "_default").css("display") == "none") { if ($("#" + name + "_default").css("display") == "none") {
$("#" + name + "_default").css("display", "inline"); $("#" + name + "_default").css("display", "flex");
} else { } else {
$("#" + name + "_default").css("display", "none"); $("#" + name + "_default").css("display", "none");
} }
if ($("#" + name + "_manual").css("display") == "none") { if ($("#" + name + "_manual").css("display") == "none") {
$("#" + name + "_manual").css("display", "inline"); $("#" + name + "_manual").css("display", "flex");
} else { } else {
$("#" + name + "_manual").css("display", "none"); $("#" + name + "_manual").css("display", "none");
} }

View File

@ -22,7 +22,7 @@ function progress_task_list(id, title) {
autoOpen: false, autoOpen: false,
modal: false, modal: false,
resizable: false, resizable: false,
draggable: false, draggable: true,
closeOnEscape: true, closeOnEscape: true,
width: 800, width: 800,
height: 600, height: 600,
@ -35,19 +35,23 @@ function progress_task_list(id, title) {
// Function var. // Function var.
var handleFetchTaskList = function(err, data) { var handleFetchTaskList = function(err, data) {
if (err) { if (err) {
console.error(err);
}
if (data.error) {
// TODO: Show info about the problem. // TODO: Show info about the problem.
$elem.html(data.error);
} else {
$elem.html(data.html);
} }
$elem.html(data.html);
if (!$elem.dialog("isOpen")) $elem.dialog("open"); if (!$elem.dialog("isOpen")) $elem.dialog("open");
if (data.status != -1) {
timeoutRef = setTimeout(function() {
xhr = fetchTaskList(id, handleFetchTaskList);
}, 3000);
}
}; };
if (!$elem.dialog("isOpen"))
timeoutRef = setInterval(function() {
xhr = fetchTaskList(id, handleFetchTaskList);
}, 3000);
xhr = fetchTaskList(id, handleFetchTaskList); xhr = fetchTaskList(id, handleFetchTaskList);
} }
@ -60,12 +64,13 @@ function progress_task_list(id, title) {
function fetchTaskList(id, callback) { function fetchTaskList(id, callback) {
return jQuery.ajax({ return jQuery.ajax({
data: { data: {
page: "include/ajax/task_list.ajax", page: "godmode/servers/discovery",
progress_task_discovery: 1, wiz: "tasklist",
method: "progressTaskDiscovery",
id: id id: id
}, },
type: "POST", type: "POST",
url: "ajax.php", url: $("#ajax-url").val(),
dataType: "json", dataType: "json",
success: function(data) { success: function(data) {
callback(null, data); callback(null, data);
@ -95,12 +100,13 @@ function show_map(id, name) {
jQuery.ajax({ jQuery.ajax({
data: { data: {
page: "include/ajax/task_list.ajax", page: "godmode/servers/discovery",
showmap: 1, wiz: "tasklist",
method: "taskShowmap",
id: id id: id
}, },
type: "POST", type: "POST",
url: "ajax.php", url: $("#ajax-url").val(),
dataType: "html", dataType: "html",
success: function(data) { success: function(data) {
$("#map_task") $("#map_task")
@ -109,3 +115,106 @@ function show_map(id, name) {
} }
}); });
} }
function show_review(id, name) {
load_modal({
target: $("#task_review"),
form: "review",
url: $("#ajax-url").val(),
modal: {
title: "Review " + name,
ok: "OK",
cancel: "Cancel"
},
ajax_callback: function(data) {
var title = $("#success-str").val();
var text = "";
var failed = 0;
try {
data = JSON.parse(data);
text = data["result"];
} catch (err) {
title = $("#failed-str").val();
text = err.message;
failed = 1;
}
if (!failed && data["error"] != undefined) {
title = $("#failed-str").val();
text = data["error"];
failed = 1;
}
if (data["report"] != undefined) {
data["report"].forEach(function(item) {
text += "<br>" + item;
});
}
$("#msg").empty();
$("#msg").html(text);
$("#msg").dialog({
width: 450,
position: {
my: "center",
at: "center",
of: window,
collision: "fit"
},
maxHeight: 400,
title: title,
buttons: [
{
class:
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
text: "OK",
click: function(e) {
if (!failed) {
$(".ui-dialog-content").dialog("close");
$("#task_review").empty();
location.reload();
} else {
$(this).dialog("close");
}
}
}
]
});
},
extradata: [
{
name: "id",
value: id
},
{
name: "wiz",
value: "tasklist"
}
],
onshow: {
page: "godmode/servers/discovery",
method: "showTaskReview",
maxHeight: 800
},
onsubmit: {
page: "godmode/servers/discovery",
method: "parseTaskReview"
}
});
}
function force_task_run(url) {
window.location = url;
}
function force_task(url, ask) {
if (ask != undefined) {
confirmDialog({
title: ask.title,
message: ask.message,
onAccept: function() {
force_task_run(url);
}
});
} else {
force_task_run(url);
}
}

View File

@ -319,6 +319,21 @@ function load_modal(settings) {
contentType: false, contentType: false,
data: data, data: data,
success: function(data) { success: function(data) {
if (settings.onshow.parser) {
data = settings.onshow.parser(data);
} else {
data = (function(d) {
try {
d = JSON.parse(d);
} catch (e) {
// Not JSON
return d;
}
if (d.error) return d.error;
if (d.result) return d.result;
})(data);
}
settings.target.html(data); settings.target.html(data);
if (settings.onload != undefined) { if (settings.onload != undefined) {
settings.onload(data); settings.onload(data);
@ -338,6 +353,12 @@ function load_modal(settings) {
? settings.onshow.maxHeight ? settings.onshow.maxHeight
: "auto", : "auto",
overlay: settings.modal.overlay, overlay: settings.modal.overlay,
position: {
my: "top+20%",
at: "top",
of: window,
collision: "fit"
},
buttons: required_buttons, buttons: required_buttons,
closeOnEscape: true, closeOnEscape: true,
open: function() { open: function() {
@ -386,6 +407,7 @@ function confirmDialog(settings) {
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel", "ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel",
click: function() { click: function() {
$(this).dialog("close"); $(this).dialog("close");
$(this).remove();
if (typeof settings.onDeny == "function") settings.onDeny(); if (typeof settings.onDeny == "function") settings.onDeny();
} }
}, },
@ -395,6 +417,7 @@ function confirmDialog(settings) {
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next", "ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
click: function() { click: function() {
$(this).dialog("close"); $(this).dialog("close");
$(this).remove();
if (typeof settings.onAccept == "function") settings.onAccept(); if (typeof settings.onAccept == "function") settings.onAccept();
} }
} }

View File

@ -0,0 +1,441 @@
/**
* IMPORTANT. Official plugin does not allow string ids
* This modificated one yes.
*/
!(function(e) {
var t = {};
function i(s) {
if (t[s]) return t[s].exports;
var n = (t[s] = { i: s, l: !1, exports: {} });
return e[s].call(n.exports, n, n.exports, i), (n.l = !0), n.exports;
}
(i.m = e),
(i.c = t),
(i.d = function(e, t, s) {
i.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: s });
}),
(i.r = function(e) {
"undefined" != typeof Symbol &&
Symbol.toStringTag &&
Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }),
Object.defineProperty(e, "__esModule", { value: !0 });
}),
(i.t = function(e, t) {
if ((1 & t && (e = i(e)), 8 & t)) return e;
if (4 & t && "object" == typeof e && e && e.__esModule) return e;
var s = Object.create(null);
if (
(i.r(s),
Object.defineProperty(s, "default", { enumerable: !0, value: e }),
2 & t && "string" != typeof e)
)
for (var n in e)
i.d(
s,
n,
function(t) {
return e[t];
}.bind(null, n)
);
return s;
}),
(i.n = function(e) {
var t =
e && e.__esModule
? function() {
return e.default;
}
: function() {
return e;
};
return i.d(t, "a", t), t;
}),
(i.o = function(e, t) {
return Object.prototype.hasOwnProperty.call(e, t);
}),
(i.p = ""),
i((i.s = 0));
})([
function(e, t, i) {
"use strict";
i.r(t);
i(1);
!(function(e, t) {
if (!e || !e.document) throw new Error("simTree need window");
!(function(e) {
var t,
i = e.document,
s = {
linkParent: !1,
response: {
name: "name",
id: "id",
pid: "pid",
checked: "checked",
open: "open",
disabled: "disabled"
}
},
n = function(e) {
throw new Error(e);
},
a = function(e, t) {
return e.replace(/\{\{(.+?)\}\}/g, function(e, i) {
return t[i] ? t[i] : "";
});
},
r = function e(t) {
if (
("undefined" == typeof $ && n("simTreeneed jquery"),
$.isPlainObject(t))
) {
if ((t.el || n("你没有传el"), !(this instanceof e)))
return new e(t);
(this.options = $.extend(!0, {}, s, t)), this.init();
}
},
d = [],
o = [];
(r.prototype = {
version: "0.0.2",
constructor: r,
on: function(e, t, i) {
var s, n;
return (
(this.handles[e] = this.handles[e] || []),
(s = this.handles[e].isTriggered),
(n = this.handles[e].args),
$.isFunction(t) &&
(!0 === i ? (this.handles[e] = [t]) : this.handles[e].push(t),
s && t.call(this, n)),
this
);
},
off: function(e) {
return (this.handles[e] = []), this;
},
trigger: function(e, t) {
var i, s;
for (
this.handles[e] = this.handles[e] || [],
i = 0,
s = this.handles[e].length,
this.handles[e].isTriggered = !0,
this.handles[e].args = t;
i < s;
i++
)
this.handles[e][i].call(this, t);
},
init: function() {
var e = this.options,
t = e.data;
(this.handles = {}),
(this.$el = $(e.el)),
(this.data = t),
this.event(),
this.render();
},
dataCallback: function() {
var e = arguments;
1 === e.length ? this.render(e[0]) : this.doRender(e[0], e[1]);
},
parse: function(e) {
var t = this.options,
i = t.response,
s = [],
n = {},
a = 0,
r = e.length,
d = i.id,
o = i.pid;
if (t.childNodeAsy) return e;
for (; a < r; a++) {
var h = e[a],
c = h[d];
if (h.children) return e;
c && (n[c] = h);
}
for (a = 0; a < r; a++) {
var h = e[a],
l = h[o],
u = n[l];
l && u ? (u.children || (u.children = [])).push(h) : s.push(h);
}
return s;
},
render: function(e) {
var e = e || this.data;
$.isFunction(e) && e({}, this.dataCallback.bind(this)),
$.isArray(e) && ((e = this.parse(e)), this.doRender(this.$el, e));
},
doRender: function(e, t, s) {
var n,
r,
h,
c,
l,
u = this,
f = this.options,
p = f.response,
m = t.length,
g = 0,
v = p.id,
k = p.name,
s = s || 1,
C =
'<i data-type="{{asy}}" class="sim-tree-spread {{spreadIcon}}"></i><a href="javascript:;"><i class="sim-tree-checkbox"></i>{{text}}</a>',
b = e === this.$el,
y = $(i.createElement("ul")),
w = f.childNodeAsy ? "asy" : "";
for (
f.check ||
(C = C.replace('<i class="sim-tree-checkbox"></i>', ""));
g < m;
g++
)
(n = t[g]),
(r = i.createElement("li")),
(c = !!n.children),
(l = n[p.disabled]),
(r.innerHTML = a(C, {
asy: w,
text: n[k],
spreadIcon: c ? "sim-icon-r" : "hidden"
})),
r.setAttribute("data-level", s),
r.setAttribute("data-id", n[v]),
l && r.setAttribute("class", "disabled"),
(h = $(r)).data("data", n),
y.append(h),
c && this.doRender(h, n.children, s + 1),
n[p.checked] && d.push(n[v]),
n[p.open] && o.push(n[v]);
m && e.append(y),
b
? (y.addClass("sim-tree"),
this.trigger("done", t),
$.each(o, function(e, t) {
u.expandNode(t);
}),
this.setSelected(d))
: f.childNodeAsy &&
(this.hideLoading(e.find(".sim-tree-spread")),
y.addClass("show"));
},
event: function() {
var e = this;
this.$el.off("click").on("click", function(t) {
var i = $(t.target);
return (
i.hasClass("sim-tree-spread") && e.spread.call(e, i),
i.hasClass("sim-tree-checkbox") && (i = i.parent()),
"a" === i[0].tagName.toLowerCase() && e.clickNode.call(e, i),
!1
);
}),
this.$el.on("selectstart", function() {
return !1;
}),
this.options.done && this.on("done", this.options.done),
this.options.onClick && this.on("click", this.options.onClick),
this.options.onChange && this.on("change", this.options.onChange),
this.options.onSearch && this.on("search", this.options.onSearch);
},
spread: function(e) {
e.hasClass("sim-icon-r")
? this.doSpread(e, !0)
: this.doSpread(e, !1);
},
showLoading: function(e) {
e.addClass("sim-loading");
},
hideLoading: function(e) {
e.removeClass("sim-loading");
},
doSpread: function(e, t) {
var i = e.parent(),
s = i.children("ul"),
n = i.data("data");
n.children &&
(t
? (e.removeClass("sim-icon-r").addClass("sim-icon-d"),
"asy" === e.data("type") &&
$.isFunction(this.data) &&
(this.showLoading(e),
this.data(i.data("data"), this.dataCallback.bind(this, i)),
e.data("type", "")),
s.addClass("show"))
: (e.removeClass("sim-icon-d").addClass("sim-icon-r"),
s.removeClass("show")));
},
clickNode: function(e) {
var i,
s,
n,
a = this,
r = e.parent(),
d = this.$el.find("li"),
o = d.length,
h = 0,
c = [],
l = !1;
if (!r.hasClass("disabled")) {
if (this.options.check)
for (
l = !0,
this.doCheck(e.find(".sim-tree-checkbox")),
this.options.linkParent &&
((s = r.children("ul")),
(n = s.find(".sim-tree-checkbox")),
$.each(n, function() {
a.doCheck($(this), r.data("checked"), !0);
}));
h < o;
h++
)
!0 === (i = d.eq(h).data()).checked && c.push(i.data);
else
t && t.css("font-weight", "normal"),
e.css("font-weight", "bold"),
(t = e),
(i = r.data("data")),
(c = [i]),
(l = !this.sels || !(this.sels[0] === i));
(this.sels = c),
this.trigger("click", c),
l && this.trigger("change", c);
}
},
doCheck: function(e, t, i) {
var s = e.closest("li"),
n = s.data();
void 0 === t && (t = !n.checked),
!0 === t
? e.removeClass("sim-tree-semi").addClass("checked")
: !1 === t
? e.removeClass("checked sim-tree-semi")
: "semi" === t &&
e.removeClass("checked").addClass("sim-tree-semi"),
s.data("checked", t),
!0 === this.options.linkParent && !i && this.setParentCheck(s);
},
setParentCheck: function(e) {
var t,
i = e.parent("ul"),
s = i.parent("li"),
n = i.children("li"),
a = s.find(">a .sim-tree-checkbox"),
r = [],
d = n.length;
s.length &&
(e.find(">a .sim-tree-checkbox").hasClass("sim-tree-semi")
? this.doCheck(a, "semi")
: ($.each(n, function() {
!0 === $(this).data("checked") && r.push($(this));
}),
(t = r.length),
d === t && this.doCheck(a, !0),
t || this.doCheck(a, !1),
t >= 1 && t < d && this.doCheck(a, "semi")));
},
search: function(e) {
if (this.$el) {
var t,
i,
s,
e = $.trim(e),
n = this.$el.find("li"),
a = 0,
r = n.length,
d = [],
o = new RegExp(e, "i");
for (
n
.hide()
.children(".sim-tree-spread")
.addClass("hidden");
a < r;
a++
)
(i = n.eq(a)),
(t = i.children("a").text()),
(s = i.data("data")),
e
? -1 !== t.search(o) &&
(1 !== parseInt(i.data("level")) &&
this.expandNode(s[this.options.response.pid]),
i
.parents("li")
.add(i)
.show(),
d.push(i))
: (i.show(),
s.children &&
i.children(".sim-tree-spread").removeClass("hidden"));
this.trigger("search", e);
}
},
expandNode: function(e) {
var t = e.addClass ? e : this.$el.find("[data-id='" + e + "']"),
i = t.data("data"),
s = i[this.options.response.pid],
n = t.children(".sim-tree-spread"),
a = parseInt(t.data("level"));
i.children &&
n.length &&
(n.removeClass("hidden"), this.doSpread(n, !0)),
1 !== a && this.expandNode(s);
},
setSelected: function(e) {
var t = this,
i = e,
s = [],
n = [];
("string" != typeof i && "number" != typeof i) || (i = [i]),
$.isArray(i) &&
(this.options.check || (i = [i[0]]),
$.each(i, function(e, i) {
var a = t.$el.find("[data-id='" + i + "']"),
r = a.children("a"),
d = r.children(".sim-tree-checkbox"),
o = a.data("data");
if (!a.length) return !0;
d.length ? t.doCheck(d, !0) : r.css("font-weight", "bold"),
1 !== parseInt(a.data("level")) &&
t.expandNode(o[t.options.response.pid]),
s.push(o),
n.push(a[0]);
}),
(t.sels = s),
t.trigger("click", s));
},
getSelected: function() {
return this.sels;
},
disableNode: function(e) {
var t = this,
i = e;
("string" != typeof i && "number" != typeof i) || (i = [i]),
$.isArray(i) &&
$.each(i, function(e, i) {
var s = t.$el.find("[data-id='" + i + "']");
s.addClass("disabled");
});
},
destroy: function() {
for (var e in (this.$el.html(""), this)) delete this[e];
},
refresh: function(e) {
this.$el.html(""), this.render(e);
}
}),
(e.simTree = r),
($.fn.simTree = function(e) {
return (e = $.extend(!0, { el: this }, e)), r(e);
});
})(e);
})("undefined" != typeof window ? window : void 0);
},
function(e, t, i) {}
]);

View File

@ -416,7 +416,12 @@ class EventsListWidget extends Widget
$filter['limit'] = $this->values['limit']; $filter['limit'] = $this->values['limit'];
$filter['order'] = '`utimestamp` DESC'; $filter['order'] = '`utimestamp` DESC';
if ((int) $this->values['severity'] !== -1) { if ((int) $this->values['severity'] === 20) {
$filter['criticity'] = [
EVENT_CRIT_WARNING,
EVENT_CRIT_CRITICAL,
];
} else if ((int) $this->values['severity'] !== -1) {
$filter['criticity'] = $this->values['severity']; $filter['criticity'] = $this->values['severity'];
} }

View File

@ -309,12 +309,6 @@ class GraphModuleHistogramWidget extends Widget
$size = parent::getSize(); $size = parent::getSize();
// Desactive scroll bars only this item. // Desactive scroll bars only this item.
$output .= '<style type="text/css">
.grid-stack-item .grid-stack-item-content .content-widget {
overflow-x: hidden;
overflow-y: hidden;
}
</style>';
$id_agent = $this->values['agentId']; $id_agent = $this->values['agentId'];
$id_module = $this->values['moduleId']; $id_module = $this->values['moduleId'];
$period = $this->values['period']; $period = $this->values['period'];

View File

@ -206,9 +206,9 @@ class MapsMadeByUser extends Widget
$fields = \visual_map_get_user_layouts($config['id_user'], true); $fields = \visual_map_get_user_layouts($config['id_user'], true);
// Event Type. // Visual console.
$inputs[] = [ $inputs[] = [
'label' => __('Event type'), 'label' => __('Visual console'),
'arguments' => [ 'arguments' => [
'type' => 'select', 'type' => 'select',
'fields' => $fields, 'fields' => $fields,

View File

@ -439,7 +439,7 @@ class SystemGroupStatusWidget extends Widget
} }
} }
$height = (count($result_groups) * 30); $height = (count($table->data) * 30);
$style = 'min-width:200px; min-height:'.$height.'px;'; $style = 'min-width:200px; min-height:'.$height.'px;';
$output = '<div class="container-center" style="'.$style.'">'; $output = '<div class="container-center" style="'.$style.'">';
if ($flag_groups === true) { if ($flag_groups === true) {

View File

@ -339,10 +339,8 @@ table.widget_maps_status tr td:first-child {
table.widget_maps_status tr td a { table.widget_maps_status tr td a {
font-family: "lato-lighter", "Open Sans", sans-serif; font-family: "lato-lighter", "Open Sans", sans-serif;
letter-spacing: 0.03pt; letter-spacing: 0.03pt;
font-size: 11pt; font-size: 9pt;
text-decoration: none; text-decoration: none;
color: #3f3f3f;
font-weight: bolder;
} }
table.widget_maps_status tr td img { table.widget_maps_status tr td img {

View File

@ -169,6 +169,7 @@ span.breadcrumb_link {
form.discovery * { form.discovery * {
font-size: 10pt; font-size: 10pt;
font-family: "lato", "Open Sans", sans-serif;
} }
form.discovery .label_select b { form.discovery .label_select b {

View File

@ -1,3 +1,14 @@
/* /*
* TODO: This may be at hostdevices.css * TODO: This may be at hostdevices.css
*/ */
select.select_multiple {
min-width: 500px;
width: 50%;
height: 250px;
}
.indented select.select_multiple {
min-width: calc(500px - 1em);
width: calc(50% - 1em);
}

View File

@ -0,0 +1,146 @@
/* surrounding tag container */
.tag-editor {
list-style-type: none;
padding: 0 5px 0 0;
margin: 0;
overflow: hidden;
border: 1px solid #eee;
cursor: text;
font: normal 14px sans-serif;
color: #555;
background: #fff;
line-height: 20px;
}
/* core styles usually need no change */
.tag-editor li {
display: block;
float: left;
overflow: hidden;
margin: 3px 0;
}
.tag-editor div {
float: left;
padding: 0 4px;
}
.tag-editor .placeholder {
padding: 0 8px;
color: #bbb;
}
.tag-editor .tag-editor-spacer {
padding: 0;
width: 8px;
overflow: hidden;
color: transparent;
background: none;
}
.tag-editor input {
vertical-align: inherit;
border: 0;
outline: none;
padding: 0;
margin: 0;
cursor: text;
font-family: inherit;
font-weight: inherit;
font-size: inherit;
font-style: inherit;
box-shadow: none;
background: none;
color: #444;
}
/* hide original input field or textarea visually to allow tab navigation */
.tag-editor-hidden-src {
position: absolute !important;
left: -99999px;
}
/* hide IE10 "clear field" X */
.tag-editor ::-ms-clear {
display: none;
}
/* tag style */
.tag-editor .tag-editor-tag {
padding-left: 5px;
color: #46799b;
background: #e0eaf1;
white-space: nowrap;
overflow: hidden;
cursor: pointer;
border-radius: 2px 0 0 2px;
}
/* delete icon */
.tag-editor .tag-editor-delete {
background: #e0eaf1;
cursor: pointer;
border-radius: 0 2px 2px 0;
padding-left: 3px;
padding-right: 4px;
}
.tag-editor .tag-editor-delete i {
line-height: 18px;
display: inline-block;
}
.tag-editor .tag-editor-delete i:before {
font-size: 16px;
color: #8ba7ba;
content: "×";
font-style: normal;
}
.tag-editor .tag-editor-delete:hover i:before {
color: #d65454;
}
.tag-editor .tag-editor-tag.active + .tag-editor-delete,
.tag-editor .tag-editor-tag.active + .tag-editor-delete i {
visibility: hidden;
cursor: text;
}
.tag-editor .tag-editor-tag.active {
background: none !important;
}
/* jQuery UI autocomplete - code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css */
.ui-autocomplete {
position: absolute;
top: 0;
left: 0;
cursor: default;
font-size: 14px;
}
.ui-front {
z-index: 9999;
}
.ui-menu {
list-style: none;
padding: 1px;
margin: 0;
display: block;
outline: none;
}
.ui-menu .ui-menu-item a {
text-decoration: none;
display: block;
padding: 2px 0.4em;
line-height: 1.4;
min-height: 0; /* support: IE7 */
}
.ui-widget-content {
border: 1px solid #bbb;
background: #fff;
color: #555;
}
.ui-widget-content a {
color: #46799b;
}
.ui-widget-content .ui-state-hover,
.ui-widget-header .ui-state-hover,
.ui-state-focus,
.ui-widget-content .ui-state-focus,
.ui-widget-header .ui-state-focus {
background: #e0eaf1;
}
.ui-helper-hidden-accessible {
display: none;
}

View File

@ -628,6 +628,9 @@ select:-internal-list-box {
.float-right { .float-right {
float: right; float: right;
} }
.invisible {
display: none;
}
div#page { div#page {
background: #fbfbfb; background: #fbfbfb;
@ -5647,6 +5650,11 @@ div#status_pie {
.white_table_graph_header b { .white_table_graph_header b {
font-size: 10pt; font-size: 10pt;
font-weight: 600; font-weight: 600;
width: 100%;
}
.white_table_graph_header div.white_table_header_checkbox {
float: right;
} }
.white_table_graph_header div#bullets_modules { .white_table_graph_header div#bullets_modules {

View File

@ -0,0 +1,38 @@
ul.wizard li > label:not(.p-switch) {
width: auto;
}
form.top-action-buttons ul.wizard {
display: flex;
flex-direction: row;
}
ul.wizard li {
margin-right: 1em;
}
form.modal ul.wizard li {
display: flex;
flex-direction: row;
width: 90%;
margin: 0 auto;
justify-items: center;
}
form.modal ul.wizard li * {
flex: 1;
}
ul.wizard li.flex-indep {
flex: 1;
margin: 0;
}
div#div-form {
padding: 0 2em;
}
div#div-form textarea {
width: 100%;
margin-top: 1em;
}

View File

@ -0,0 +1,124 @@
.sim-tree {
list-style: none;
font-size: 14px;
color: #333;
}
.sim-tree ul,
.sim-tree li {
margin: 0;
padding: 0;
}
.sim-tree li {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
font-size: 0;
}
.sim-tree li ul {
display: none;
margin-left: 15px;
}
.sim-tree ul.show,
.sim-tree li.show {
display: block;
}
.sim-tree ul.none,
.sim-tree li.none {
display: none;
}
.sim-tree li.disabled > a {
color: #aaa;
cursor: not-allowed;
}
.sim-tree li.disabled > a .sim-tree-checkbox {
border-color: #eee;
}
.sim-tree a {
font-size: 14px;
color: #333;
text-decoration: none;
vertical-align: top;
line-height: 26px;
}
.sim-tree .sim-tree-spread {
width: 20px;
padding-left: 5px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.sim-tree .sim-tree-spread.hidden {
visibility: hidden;
}
.sim-tree .sim-tree-spread,
.sim-tree a {
display: inline-block;
height: 26px;
cursor: pointer;
}
.sim-tree .sim-loading {
background: url(data:image/gif;base64,R0lGODlhEAAQAMQQAObm5uLi4unp6dHR0cnJydfX1+jo6O/v7/Dw8NPT0/39/crKyvr6+uDg4MfHx////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAQACwAAAAAEAAQAAAFXeAjPkiTjGgaLI6Tvs9BtPAIMPH8KgK5DDhZSlFYlFrAGIrYMrUcyRGzdapZr6jE02FAyZ6JxrOrEAVnjgaCRS6IkjLjo9F2PaDBwLJAu+NfAix2LQsAMCVVYQgoIQAh+QQFAAAQACwJAAAABwAHAAAFFGDSIE/5OM7SmKhjsK55vjIt32UIACH5BAUAABAALAoAAwAGAAoAAAUaICQqgggpxYKcheM0qOskZm0/eA7luMibvRAAIfkEBQAAEAAsCQAJAAcABwAABRXgcxBOmTwi6TRouiAoIwbtI9d4/oQAIfkEBQAAEAAsAwAKAAoABgAABRsgJI7MKD6POJQnKjpD60IODKFzvQD3nDQISAgAIfkEBQAAEAAsAAAJAAcABwAABRPgI45kSSrFWTgj6rCisLwk0iQhACH5BAUAABAALAAAAwAHAAoAAAUcIPRAJPmco4mm61m+cJk4tGNATX0ryGK/jVspBAAh+QQFAAAQACwAAAAABwAHAAAFFOAjjmRpPgBDIsugio3juGIiz2oIADs=)
center center no-repeat;
}
.sim-tree .sim-loading.sim-icon-d:before,
.sim-tree .sim-loading.sim-icon-r:before {
display: none;
}
.sim-tree .sim-icon-d:before,
.sim-tree .sim-icon-r:before {
content: "";
display: inline-block;
width: 0;
height: 0;
border: 6px solid transparent;
vertical-align: top;
position: relative;
}
.sim-tree .sim-icon-r:before {
border-left-width: 8px;
border-left-color: #333;
top: 7px;
}
.sim-tree .sim-icon-d:before {
margin-left: -4px;
border-top-color: #333;
top: 10px;
}
.sim-tree .sim-tree-checkbox {
display: inline-block;
border: 1px solid #ccc;
height: 16px;
width: 16px;
border-radius: 3px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
text-align: center;
line-height: 16px;
background: #fff;
color: #fff;
vertical-align: middle;
margin-right: 6px;
margin-top: -2px;
}
.sim-tree .sim-tree-checkbox.sim-tree-semi,
.sim-tree .sim-tree-checkbox.checked {
border-color: #2b85e4;
background-color: #2b85e4;
}
.sim-tree .sim-tree-checkbox.sim-tree-semi {
position: relative;
}
.sim-tree .sim-tree-checkbox.sim-tree-semi:after {
content: "";
display: block;
position: absolute;
width: 8px;
height: 2px;
background: #fff;
top: 6px;
left: 3px;
}
.sim-tree .sim-tree-checkbox.checked {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAMAAABhq6zVAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAAD///////////////////////////////////////////////////////////////////////8AAADY904BAAAAE3RSTlMAOiE8877cHQkXr9cZQvUc20NAbrhSVAAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAA7SURBVAjXY2DADhiZEGxmFlYkNhs7KpuDE0mci5sHoYaXj5sHyOaHqOblE4CzGRgE+RBsBgYhfmxuAABcBQF5T7U3IwAAAABJRU5ErkJggg==);
background-repeat: no-repeat;
background-position: center center;
}

View File

@ -36,7 +36,77 @@ ul.progress_task_discovery {
flex-direction: column; flex-direction: column;
} }
div.subtitle {
width: 100%;
margin-top: 40px;
text-align: center;
}
div.subtitle span {
font-size: 1.9em;
font-family: "lato-bolder", "Open Sans", sans-serif;
}
div.subtitle div.manage {
text-align: center;
padding-top: 2em;
padding-bottom: 1em;
}
div.subtitle div.manage button {
font-size: 1.2em;
font-family: "lato", "Open Sans", sans-serif;
display: inline-block;
margin-right: 1em;
cursor: pointer;
text-align: left;
border-radius: 21px;
box-shadow: 0 0 10px -5px #888;
padding: 0.5em 1em;
border: 1px solid #ddd;
user-select: none;
color: #424242;
}
div.subtitle .link.review {
margin: 15px 0 -30px;
display: block;
font-weight: bold;
}
#msg ul li {
margin-left: 3em;
}
li.added {
list-style: url("../../images/header_ready.png");
}
li.removed {
list-style: url("../../images/header_down.png");
}
#msg ul {
list-style: url("../../images/header_ready.png");
}
ul.progress_task_discovery li span { ul.progress_task_discovery li span {
font-size: 9pt; font-size: 9pt;
margin-left: 20px; margin-left: 20px;
} }
.ui-dialog.ui-widget-content {
cursor: initial;
}
span.link {
cursor: pointer;
}
span.link.review {
font-weight: bold;
}
#review {
padding-top: 2em;
padding-left: 6.7em;
}

View File

@ -2,7 +2,11 @@
* Discovery > Wizard css global style * Discovery > Wizard css global style
*/ */
#main > form.discovery.wizard > .white_box {
min-width: 1024px;
}
ul.wizard { ul.wizard {
list-style-type: none;
} }
ul.wizard li { ul.wizard li {
@ -23,6 +27,100 @@ ul.wizard li > textarea {
font-family: monospace; font-family: monospace;
} }
.hidden { .wizard .hidden {
display: none; display: none;
} }
.wizard .indented {
margin-left: 1em;
}
.wizard .std_input {
display: flex;
margin-bottom: 25px;
flex-wrap: wrap;
justify-content: space-between;
}
.wizard .std_input > .label_select {
flex: 1 1 100%;
}
.wizard .std_input > * {
flex: 1 1 auto;
align-self: baseline;
}
.wizard .inline_input.no-margin {
margin-bottom: 0px;
}
.wizard .inline_input {
display: flex;
margin-bottom: 25px;
flex-wrap: wrap;
justify-content: space-between;
align-items: baseline;
}
.wizard .inline_input * {
flex: 1 1 auto;
}
.wizard .discovery_inline_input {
display: flex;
align-content: end;
flex: 0;
align-self: flex-start;
}
/* override tag-editor styles */
.wizard .tag-editor.ui-sortable {
width: 450px;
display: inline-block;
}
.wizard .tag-editor .tag-editor-tag {
padding: 5px;
color: #fff;
background: #82b92e;
}
.wizard .tag-editor .tag-editor-delete i {
line-height: inherit;
}
.wizard .tag-editor .tag-editor-delete i:before {
color: #ccc;
}
.wizard .tag-editor .tag-editor-delete:hover i:before {
color: #fff;
}
.wizard .tag-editor .tag-editor-delete {
padding: 5px;
background: #e63c52;
}
.wizard .time_selection_container {
display: flex;
align-items: baseline;
justify-items: center;
align-content: space-between;
margin-top: 1em;
}
.wizard #interval_manual_container #interval_manual > * {
flex: 1 1 auto;
}
.wizard-column-levels {
float: left;
width: 33%;
text-align: center;
}
.action_button_list {
height: 60px;
}
.action_button_list li {
display: inline;
}

View File

@ -129,7 +129,7 @@
<div style='height: 10px'> <div style='height: 10px'>
<?php <?php
$version = '7.0NG.744'; $version = '7.0NG.744';
$build = '200413'; $build = '200414';
$banner = "v$version Build $build"; $banner = "v$version Build $build";
error_reporting(0); error_reporting(0);

View File

@ -57,10 +57,10 @@ if ($new_networkmap) {
$offset_x = ''; $offset_x = '';
$offset_y = ''; $offset_y = '';
$scale_z = 0.5; $scale_z = 0.5;
$node_sep = 0.1; $node_sep = 10;
$rank_sep = 1.0; $rank_sep = 1.0;
$mindist = 1.0; $mindist = 1.0;
$kval = 0.1; $kval = 5;
} }
$disabled_generation_method_select = false; $disabled_generation_method_select = false;

View File

@ -328,6 +328,8 @@ if (is_ajax()) {
$data = array_reduce( $data = array_reduce(
$events, $events,
function ($carry, $item) { function ($carry, $item) {
global $config;
$tmp = (object) $item; $tmp = (object) $item;
$tmp->meta = is_metaconsole(); $tmp->meta = is_metaconsole();
if (is_metaconsole()) { if (is_metaconsole()) {
@ -360,7 +362,10 @@ if (is_ajax()) {
true true
); );
$tmp->data = format_numeric($tmp->data, 1); $tmp->data = format_numeric(
$tmp->data,
$config['graph_precision']
);
$tmp->instructions = events_get_instructions($item); $tmp->instructions = events_get_instructions($item);

View File

@ -127,17 +127,7 @@ if ($read_message) {
).' '.$user_name; ).' '.$user_name;
} }
$order = [ $parsed_message = nl2br(htmlspecialchars(trim(io_safe_output($row['message']))));
"\r\n",
"\n",
"\r",
];
$replace = '<br />';
$parsed_message = str_replace(
$order,
$replace,
trim(io_safe_output($row['message']))
);
echo '<div class="container">'; echo '<div class="container">';
echo ' <p>'.$parsed_message.'</p>'; echo ' <p>'.$parsed_message.'</p>';

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_console %define name pandorafms_console
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
# User and Group under which Apache is running # User and Group under which Apache is running
%define httpd_name httpd %define httpd_name httpd

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_console %define name pandorafms_console
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
# User and Group under which Apache is running # User and Group under which Apache is running
%define httpd_name httpd %define httpd_name httpd

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_console %define name pandorafms_console
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
%define httpd_name httpd %define httpd_name httpd
# User and Group under which Apache is running # User and Group under which Apache is running
%define httpd_name apache2 %define httpd_name apache2

View File

@ -773,14 +773,14 @@ CREATE TABLE IF NOT EXISTS `trecon_task` (
`name` varchar(100) NOT NULL default '', `name` varchar(100) NOT NULL default '',
`description` varchar(250) NOT NULL default '', `description` varchar(250) NOT NULL default '',
`subnet` text NOT NULL, `subnet` text NOT NULL,
`id_network_profile` int(10) unsigned NOT NULL default '0', `id_network_profile` text,
`create_incident` tinyint(3) unsigned NOT NULL default '0', `review_mode` tinyint(1) unsigned NOT NULL default 1,
`id_group` int(10) unsigned NOT NULL default '1', `id_group` int(10) unsigned NOT NULL default 1,
`utimestamp` bigint(20) unsigned NOT NULL default '0', `utimestamp` bigint(20) unsigned NOT NULL default 0,
`status` tinyint(4) NOT NULL default '0', `status` tinyint(4) NOT NULL default 0,
`interval_sweep` int(10) unsigned NOT NULL default '0', `interval_sweep` int(10) unsigned NOT NULL default 0,
`id_recon_server` int(10) unsigned NOT NULL default '0', `id_recon_server` int(10) unsigned NOT NULL default 0,
`id_os` tinyint(4) NOT NULL default '0', `id_os` tinyint(4) NOT NULL default 0,
`recon_ports` varchar(250) NOT NULL default '', `recon_ports` varchar(250) NOT NULL default '',
`snmp_community` varchar(64) NOT NULL default 'public', `snmp_community` varchar(64) NOT NULL default 'public',
`id_recon_script` int(10), `id_recon_script` int(10),
@ -788,31 +788,59 @@ CREATE TABLE IF NOT EXISTS `trecon_task` (
`field2` varchar(250) NOT NULL default '', `field2` varchar(250) NOT NULL default '',
`field3` varchar(250) NOT NULL default '', `field3` varchar(250) NOT NULL default '',
`field4` varchar(250) NOT NULL default '', `field4` varchar(250) NOT NULL default '',
`os_detect` tinyint(1) unsigned default '0', `os_detect` tinyint(1) unsigned default 0,
`resolve_names` tinyint(1) unsigned default '0', `resolve_names` tinyint(1) unsigned default 0,
`parent_detection` tinyint(1) unsigned default '0', `parent_detection` tinyint(1) unsigned default 0,
`parent_recursion` tinyint(1) unsigned default '0', `parent_recursion` tinyint(1) unsigned default 0,
`disabled` tinyint(1) unsigned NOT NULL DEFAULT '0', `disabled` tinyint(1) unsigned NOT NULL DEFAULT 0,
`macros` TEXT, `macros` TEXT,
`alias_as_name` tinyint(2) NOT NULL default '0', `alias_as_name` tinyint(2) NOT NULL default 0,
`snmp_enabled` tinyint(1) unsigned default '0', `snmp_enabled` tinyint(1) unsigned default 0,
`vlan_enabled` tinyint(1) unsigned default '0', `vlan_enabled` tinyint(1) unsigned default 0,
`snmp_version` varchar(5) NOT NULL default '1', `snmp_version` varchar(5) NOT NULL default 1,
`snmp_auth_user` varchar(255) NOT NULL default '', `snmp_auth_user` varchar(255) NOT NULL default '',
`snmp_auth_pass` varchar(255) NOT NULL default '', `snmp_auth_pass` varchar(255) NOT NULL default '',
`snmp_auth_method` varchar(25) NOT NULL default '', `snmp_auth_method` varchar(25) NOT NULL default '',
`snmp_privacy_method` varchar(25) NOT NULL default '', `snmp_privacy_method` varchar(25) NOT NULL default '',
`snmp_privacy_pass` varchar(255) NOT NULL default '', `snmp_privacy_pass` varchar(255) NOT NULL default '',
`snmp_security_level` varchar(25) NOT NULL default '', `snmp_security_level` varchar(25) NOT NULL default '',
`wmi_enabled` tinyint(1) unsigned DEFAULT '0', `wmi_enabled` tinyint(1) unsigned DEFAULT 0,
`auth_strings` text, `auth_strings` text,
`autoconfiguration_enabled` tinyint(1) unsigned default '0', `auto_monitor` TINYINT(1) UNSIGNED DEFAULT 1,
`autoconfiguration_enabled` tinyint(1) unsigned default 0,
`summary` text, `summary` text,
`type` int NOT NULL default 0, `type` int NOT NULL default 0,
`subnet_csv` TINYINT(1) UNSIGNED DEFAULT 0,
PRIMARY KEY (`id_rt`), PRIMARY KEY (`id_rt`),
KEY `recon_task_daemon` (`id_recon_server`) KEY `recon_task_daemon` (`id_recon_server`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tdiscovery_tmp`
-- ----------------------------------------------------------------------
CREATE TABLE `tdiscovery_tmp_agents` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`label` varchar(600) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`data` MEDIUMTEXT,
`review_date` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_rt` (`id_rt`),
INDEX `label` (`label`),
CONSTRAINT `tdta_trt` FOREIGN KEY (`id_rt`) REFERENCES `trecon_task` (`id_rt`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tdiscovery_tmp_connections` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`dev_1` text,
`dev_2` text,
`if_1` text,
`if_2` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
-- Table `tmodule_relationship` -- Table `tmodule_relationship`
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
@ -926,6 +954,28 @@ CREATE TABLE IF NOT EXISTS `tnetwork_profile_component` (
KEY `id_np` (`id_np`) KEY `id_np` (`id_np`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tpen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tpen` (
`pen` int(10) unsigned NOT NULL,
`manufacturer` TEXT,
`description` TEXT,
PRIMARY KEY (`pen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tnetwork_profile_pen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tnetwork_profile_pen` (
`pen` int(10) unsigned NOT NULL,
`id_np` int(10) unsigned NOT NULL,
CONSTRAINT `fk_network_profile_pen_pen` FOREIGN KEY (`pen`)
REFERENCES `tpen` (`pen`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_network_profile_pen_id_np` FOREIGN KEY (`id_np`)
REFERENCES `tnetwork_profile` (`id_np`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
-- Table `tnota` -- Table `tnota`
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------

View File

@ -1594,3 +1594,123 @@ VALUES
(254,6,848,943,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0), (254,6,848,943,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0),
(255,5,846,941,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0) (255,5,846,941,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0)
; ;
--
-- Dumping data for table `tpen`
--
INSERT INTO `tpen`
VALUES
(9,'cisco','Cisco&#x20;System'),
(11,'hp','Hewlett&#x20;Packard'),
(2021,'general_snmp','U.C.&#x20;Davis,&#x20;ECE&#x20;Dept.&#x20;Tom'),
(2636,'juniper','Juniper&#x20;Networks'),
(3375,'f5','F5&#x20;Labs'),
(8072,'general_snmp','Net&#x20;SNMP'),
(12356,'fortinet','Fortinet')
;
--
-- Dumping data for table `tnetwork_profile` and `tnetwork_profile_pen`
--
SET @template_name = 'Network&#x20;Management';
SET @template_description = 'Basic network monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Network Management')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Cisco&#x20;MIBS';
SET @template_description = 'Cisco devices monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Cisco MIBS' OR g.name = 'Catalyst 2900')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 9)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Linux&#x20;System';
SET @template_description = 'Linux system monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
SET @module_group = 'Linux';
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Linux' OR g.name = 'UCD Mibs (Linux, UCD-SNMP)')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 2021 OR p.pen = 2636)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;System';
SET @template_description = 'Windows system monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Microsoft&#x20;Windows' OR g.name = 'Windows System')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Hardware';
SET @template_description = 'Windows hardware monitoring templae (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Hardware Layer')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Active&#x20;Directory';
SET @template_description = 'Active directory monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows AD' OR g.name = 'AD&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;IIS';
SET @template_description = 'IIS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows IIS' OR g.name = 'IIS&#x20;services')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Exchange';
SET @template_description = 'Exchange monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Exchange' OR g.name = 'Exchange&#x20;Services' OR g.name = 'Exchange&#x20;TCP&#x20;Ports')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;LDAP';
SET @template_description = 'LDAP monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows LDAP')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MDSTC';
SET @template_description = 'MDSTC monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows MSDTC')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Printers';
SET @template_description = 'Windows printers monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Printers')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;DNS';
SET @template_description = 'Windows DNS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows&#x20;DNS' OR g.name = 'DNS&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MS&#x20;SQL&#x20;Server';
SET @template_description = 'MS SQL Server monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MS&#x20;SQL&#x20;Server')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Oracle';
SET @template_description = 'Oracle monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Oracle')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'MySQL';
SET @template_description = 'MySQL monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MySQL')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Antivirus';
SET @template_description = 'Windows antivirus monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Norton' OR g.name = 'Panda' OR g.name = 'McAfee' OR g.name = 'Bitdefender' OR g.name = 'BullGuard' OR g.name = 'AVG' OR g.name = 'Kaspersky')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);

View File

@ -1,398 +0,0 @@
#!/usr/bin/env python3
###################################################
#
# Pandora FMS Autodiscovery plugin.
# Checks the status of the services in list and monitors CPU and Memory for each of them.
#
# (c) A. Kevin Rojas <kevin.rojas@pandorafms.com>
#
# TO DO LIST:
# - Enable child services detection (Windows)
# - Make CPU/Memory usage available for child services (Windows)
#
###################################################
from sys import argv, path, stderr, exit
import psutil
from subprocess import *
global module_list
module_list = []
#########################################################################################
# Powershell class
#########################################################################################
class PSCheck:
@staticmethod
def check_service(servicename, option=False, memcpu=False):
"""Check services with powershell by parsing their DisplayName. Returns a dict\
list with the name of the service and a boolean with its status.\n
Requires service name (case insensitive)."""
pscall = Popen(["powershell", "Get-Service", "-Name", "'*"+ str(servicename) + "*'",
"|", "Select-Object", "-ExpandProperty", "Name"],
stdout=PIPE, stdin=DEVNULL, stderr=DEVNULL, universal_newlines=True)
result = pscall.communicate()
result = str(result[0]).strip().split("\n")
procname = ''
if result != '':
output = []
for element in result:
if element != '':
# Get process name
procname = PSCheck.get_serviceprocess(element)
# Get process status
parstatus = PSCheck.getstatus(element)
if memcpu == True and parstatus == 1:
usage = get_memcpu(str(procname), str(element))
output += usage
# Generate module with name and status
parent = service_module(str(element), parstatus)
output += parent
if option == True:
children = PSCheck.getchildren(element, memcpu)
if type(children) == list and len(children) > 1:
for child in children:
output += child
else:
output += children
else:
next
#if output != '':
if output and element and procname:
return ({"name" : element, "process" : procname, "modules": output})
else:
return (None)
@staticmethod
def getchildren(servicename, memcpu=False):
"""Gets Dependent services of a given Windows service"""
pschild = Popen(["powershell", "Get-Service", "-Name '" + str(servicename) +
"' -DS", "|", "Select-Object", "-ExpandProperty", "Name"],
stdout=PIPE, stdin=DEVNULL, stderr=DEVNULL, universal_newlines=True)
children = pschild.communicate()[0].strip()
kids = []
for child in (children.split("\n") if children != "" else []):
status = PSCheck.getstatus(child)
kids += service_module(str(child), status, "Service " + str(servicename) + " - Status")
if status:
if memcpu == True:
kidsusage = get_memcpu(str(child))
for usage in kidsusage:
kids += usage
else:
next
return (kids)
@staticmethod
def getstatus(servicename):
"""Gets the status of a given Windows service"""
running = Popen(["powershell", "Get-Service", "-Name '" + str(servicename) +
"' |", "Select-Object", "-ExpandProperty", "Status"],
stdout=PIPE, stdin=DEVNULL, stderr=DEVNULL, universal_newlines=True)
status = running.communicate()[0].strip()
return (int(status == "Running"))
@staticmethod
def get_serviceprocess(servicename):
"""Gets name of the process of the service"""
service = psutil.win_service_get(servicename)
srv_pid = service.pid()
process = psutil.Process(srv_pid)
proc_name = process.name()
return (proc_name)
#########################################################################################
# Services creation
#########################################################################################
def service_module(name, value, parent=None):
#print ("service_module BEGIN "+str(now(0,1)))
module = [{
"name" : "Service "+ name + " - Status",
"type" : "generic_proc",
"value" : value,
"module_parent" : parent,
}]
#print ("service_module END "+str(now(0,1)))
return (module)
def get_memcpu (process, servicename):
"""Creates a module for Memory and CPU for a given process. Returns a list of dictionaries."""
modules = []
if process:
if servicename != None:
parentname = servicename
else:
parentname = process
modules += [{
"name" : "Service "+ process + " - Memory usage",
"type" : "generic_data",
"value" : proc_percentbyname(process)[0],
"unit" : "%",
"module_parent" : "Service "+ parentname + " - Status",
},
{"name" : "Service "+ process + " - CPU usage",
"type" : "generic_data",
"value" : proc_percentbyname(process)[1],
"unit" : "%",
"module_parent" : "Service "+ parentname + " - Status",
}]
return (modules)
def proc_percentbyname(procname): ############# 03/03/2020
"""Gets Memory and CPU usage for a given process. Returns a list."""
#print ("proc_percentbyname BEGIN "+str(now(0,1)))
procs = [p for p in psutil.process_iter() if procname in p.name().lower()]
memory = []
cpu = []
try:
for proc in procs:
if proc.name() == procname:
cpu.append(proc.cpu_percent(interval=0.5))
memory.append(proc.memory_percent())
else:
next
except psutil.NoSuchProcess:
next
#print ("proc_percentbyname END "+str(now(0,1)))
return ([sum(memory),sum(cpu)])
def win_service(servicelist, option=False, memcpu=False):
"""Creates modules for Windows servers."""
modules = []
for srvc in servicelist:
if srvc and len(srvc) > 2:
output = PSCheck.check_service(srvc, option, memcpu)
if output != None and output["modules"]:
modules += PSCheck.check_service(srvc.strip(), option, memcpu)["modules"]
module_list.append(srvc)
winprocess = output["name"]
#if memcpu == True:
# modules += get_memcpu(winprocess) ## Only available for parent service ATM.
else:
next
else:
next
for module in modules:
print_module(module, 1)
def lnx_service(services_list, memcpu=False):
"""Creates modules for Linux servers"""
modules = []
sysctl = getstatusoutput("command -v systemctl")[0]
servic = getstatusoutput("command -v service")[0]
for srvc in services_list:
status = None
if sysctl == 0:
### Systemd available
syscall = Popen(["systemctl", "is-active", srvc], stdout=PIPE,
stdin=DEVNULL, universal_newlines=True)
result = syscall.communicate()
result = result[0].strip().lower()
if result == "active":
modules += service_module(srvc, 1)
status = 1
elif result == "inactive":
modules += service_module(srvc, 0)
status = 0
elif result == "unknown":
next
elif sysctl != 0 and servic == 0:
### Systemd not available, switch to service command
syscall = Popen(["service", srvc, "status"], stdout=PIPE,
stdin=DEVNULL, stderr=DEVNULL, universal_newlines=True)
result = syscall.communicate()[0].lower()
if "is running" in result:
modules += service_module(srvc, 1)
status = 1
elif "is stopped" in result:
modules += service_module(srvc, 0)
status = 0
else:
next
else:
print ("No systemd or service commands available. Exiting...", file=stderr)
exit()
if status:
module_list.append(srvc)
if memcpu == True:
modules += get_memcpu(srvc, None)
for m in modules:
print_module (m, 1)
#########################################################################################
# print_module function
#########################################################################################
def print_module(module, str_flag=False):
"""Returns module in XML format. Accepts only {dict}.\n
+ Only works with one module at a time: otherwise iteration is needed.
+ Module "value" field accepts str type or [list] for datalists.
+ Use not_print_flag to avoid printing the XML (only populates variables).
"""
data = dict(module)
module_xml = ("<module>\n"
"\t<name><![CDATA[" + str(data["name"]) + "]]></name>\n"
"\t<type>" + str(data["type"]) + "</type>\n"
)
#### Strip spaces if module not generic_data_string
if type(data["type"]) is not str and "string" not in data["type"]:
data["value"] = data["value"].strip()
if isinstance(data["value"], list): # Checks if value is a list
module_xml += "\t<datalist>\n"
for value in data["value"]:
if type(value) is dict and "value" in value:
module_xml += "\t<data>\n"
module_xml += "\t\t<value><![CDATA[" + str(value["value"]) + "]]></value>\n"
if "timestamp" in value:
module_xml += "\t\t<timestamp><![CDATA[" + str(value["timestamp"]) + "]]></timestamp>\n"
module_xml += "\t</data>\n"
else:
module_xml += "\t<data><![CDATA[" + str(data["value"]) + "]]></data>\n"
if "desc" in data:
module_xml += "\t<description><![CDATA[" + str(data["desc"]) + "]]></description>\n"
if "unit" in data:
module_xml += "\t<unit><![CDATA[" + str(data["unit"]) + "]]></unit>\n"
if "interval" in data:
module_xml += "\t<module_interval><![CDATA[" + str(data["interval"]) + "]]></module_interval>\n"
if "tags" in data:
module_xml += "\t<tags>" + str(data["tags"]) + "</tags>\n"
if "module_group" in data:
module_xml += "\t<module_group>" + str(data["module_group"]) + "</module_group>\n"
if "module_parent" in data and data["module_parent"] != None:
module_xml += "\t<module_parent>" + str(data["module_parent"]) + "</module_parent>\n"
if "min_warning" in data:
module_xml += "\t<min_warning><![CDATA[" + str(data["min_warning"]) + "]]></min_warning>\n"
if "max_warning" in data:
module_xml += "\t<max_warning><![CDATA[" + str(data["max_warning"]) + "]]></max_warning>\n"
if "min_critical" in data:
module_xml += "\t<min_critical><![CDATA[" + str(data["min_critical"]) + "]]></min_critical>\n"
if "max_critical" in data:
module_xml += "\t<max_critical><![CDATA[" + str(data["max_critical"]) + "]]></max_critical>\n"
if "str_warning" in data:
module_xml += "\t<str_warning><![CDATA[" + str(data["str_warning"]) + "]]></str_warning>\n"
if "str_critical" in data:
module_xml += "\t<str_critical><![CDATA[" + str(data["str_critical"]) + "]]></str_critical>\n"
if "critical_inverse" in data:
module_xml += "\t<critical_inverse><![CDATA[" + str(data["critical_inverse"]) + "]]></critical_inverse>\n"
if "warning_inverse" in data:
module_xml += "\t<warning_inverse><![CDATA[" + str(data["warning_inverse"]) + "]]></warning_inverse>\n"
if "max" in data:
module_xml += "\t<max><![CDATA[" + str(data["max"]) + "]]></max>\n"
if "min" in data:
module_xml += "\t<min><![CDATA[" + str(data["min"]) + "]]></min>\n"
if "post_process" in data:
module_xml += "\t<post_process><![CDATA[" + str(data["post_process"]) + "]]></post_process>\n"
if "disabled" in data:
module_xml += "\t<disabled><![CDATA[" + str(data["disabled"]) + "]]></disabled>\n"
if "min_ff_event" in data:
module_xml += "\t<min_ff_event><![CDATA[" + str(data["min_ff_event"]) + "]]></min_ff_event>\n"
if "status" in data:
module_xml += "\t<status><![CDATA[" + str(data["status"]) + "]]></status>\n"
if "timestamp" in data:
module_xml += "\t<timestamp><![CDATA[" + str(data["timestamp"]) + "]]></timestamp>\n"
if "custom_id" in data:
module_xml += "\t<custom_id><![CDATA[" + str(data["custom_id"]) + "]]></custom_id>\n"
if "critical_instructions" in data:
module_xml += "\t<critical_instructions><![CDATA[" + str(data["critical_instructions"]) + "]]></critical_instructions>\n"
if "warning_instructions" in data:
module_xml += "\t<warning_instructions><![CDATA[" + str(data["warning_instructions"]) + "]]></warning_instructions>\n"
if "unknown_instructions" in data:
module_xml += "\t<unknown_instructions><![CDATA[" + str(data["unknown_instructions"]) + "]]></unknown_instructions>\n"
if "quiet" in data:
module_xml += "\t<quiet><![CDATA[" + str(data["quiet"]) + "]]></quiet>\n"
if "module_ff_interval" in data:
module_xml += "\t<module_ff_interval><![CDATA[" + str(data["module_ff_interval"]) + "]]></module_ff_interval>\n"
if "crontab" in data:
module_xml += "\t<crontab><![CDATA[" + str(data["crontab"]) + "]]></crontab>\n"
if "min_ff_event_normal" in data:
module_xml += "\t<min_ff_event_normal><![CDATA[" + str(data["min_ff_event_normal"]) + "]]></min_ff_event_normal>\n"
if "min_ff_event_warning" in data:
module_xml += "\t<min_ff_event_warning><![CDATA[" + str(data["min_ff_event_warning"]) + "]]></min_ff_event_warning>\n"
if "min_ff_event_critical" in data:
module_xml += "\t<min_ff_event_critical><![CDATA[" + str(data["min_ff_event_critical"]) + "]]></min_ff_event_critical>\n"
if "ff_type" in data:
module_xml += "\t<ff_type><![CDATA[" + str(data["ff_type"]) + "]]></ff_type>\n"
if "ff_timeout" in data:
module_xml += "\t<ff_timeout><![CDATA[" + str(data["ff_timeout"]) + "]]></ff_timeout>\n"
if "each_ff" in data:
module_xml += "\t<each_ff><![CDATA[" + str(data["each_ff"]) + "]]></each_ff>\n"
if "module_parent_unlink" in data:
module_xml += "\t<module_parent_unlink><![CDATA[" + str(data["parent_unlink"]) + "]]></module_parent_unlink>\n"
if "global_alerts" in data:
for alert in data["alert"]:
module_xml += "\t<alert_template><![CDATA[" + alert + "]]></alert_template>\n"
module_xml += "</module>\n"
#### Print flag
if str_flag is not False:
print (module_xml)
return (module_xml)
#########################################################################################
# MAIN
#########################################################################################
def main():
"""Checks OS and calls the discover function."""
if psutil.WINDOWS:
OS = "Windows"
service_list = ["MySQL", "postgresql", "pgsql", "oracle", "MSSQL", "IISADMIN",
"apache", "nginx", "W3svc", "NTDS", "Netlogon", "DNS", "MSExchangeADTopology",
"MSExchangeServiceHost", "MSExchangeSA", "MSExchangeTransport"]
discover(OS, service_list)
elif psutil.LINUX:
OS = "Linux"
service_list = ["httpd", "apache2", "nginx", "ldap", "docker",
"postfix", "mysqld", "postgres", "oracle", "mongod"]
discover(OS, service_list)
else:
print ("OS not recognized. Exiting...", file=stderr)
exit()
def discover(osyst, servicelist):
"""Shows help and triggers the creation of service modules"""
if "--usage" in argv:
memcpu = True
else:
memcpu = False
if len(argv) > 2 and argv[1] == "--list":
servicelist = argv[2].split(",")
if osyst == "Windows":
win_service(servicelist, False, memcpu) ## False won't get children
elif osyst == "Linux":
lnx_service(servicelist, memcpu)
elif len(argv) > 1 and argv[1] == "--default":
if osyst == "Windows":
win_service(servicelist, False, memcpu) ## False won't get children
elif osyst == "Linux":
lnx_service(servicelist, memcpu)
else:
print ("\nPandora FMS Autodiscovery plugin.")
print ("Checks the status of the services in list and monitors CPU and Memory for each of them.\n")
print ("Usage:")
print ("{} [options] [--usage]".format(argv[0]))
print ("--help")
print ("\tPrints this help screen")
print ("--default")
print ("\tRuns this tool with default monitoring.".format(argv[0]))
print ("\tServices monitored by default for {}:".format(osyst))
print ("\t",", ".join(servicelist))
print ("--list \"<srvc1,srvc2,srvc3>\"")
print ("\tReplaces default services for a given list (comma-separated)")
if osyst == "Windows":
print ("\tEach element of the list will be treated as a regexp, but they must be over 2 characters.")
print ("\tElements under 2 characters will be discarded.")
print ("--usage")
print ("\tAdds modules for CPU and Memory usage per service/process (optional, can take some time).\n")
##### RUN ####
main()

View File

@ -1,5 +1,5 @@
package: pandorafms-server package: pandorafms-server
Version: 7.0NG.744-200413 Version: 7.0NG.744-200414
Architecture: all Architecture: all
Priority: optional Priority: optional
Section: admin Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
pandora_version="7.0NG.744-200413" pandora_version="7.0NG.744-200414"
package_cpan=0 package_cpan=0
package_pandora=1 package_pandora=1

View File

@ -45,7 +45,7 @@ our @EXPORT = qw(
# version: Defines actual version of Pandora Server for this module only # version: Defines actual version of Pandora Server for this module only
my $pandora_version = "7.0NG.744"; my $pandora_version = "7.0NG.744";
my $pandora_build = "200413"; my $pandora_build = "200414";
our $VERSION = $pandora_version." ".$pandora_build; our $VERSION = $pandora_version." ".$pandora_build;
# Setup hash # Setup hash

View File

@ -270,7 +270,9 @@ our @EXPORT = qw(
pandora_delete_custom_graph pandora_delete_custom_graph
pandora_edit_custom_graph pandora_edit_custom_graph
notification_set_targets notification_set_targets
); notification_get_users
notification_get_groups
);
# Some global variables # Some global variables
our @DayNames = qw(sunday monday tuesday wednesday thursday friday saturday); our @DayNames = qw(sunday monday tuesday wednesday thursday friday saturday);
@ -1646,6 +1648,17 @@ sub pandora_process_module ($$$$$$$$$;$) {
"' for agent " . "' for agent " .
(defined ($agent) && $agent ne '' ? "'" . safe_output($agent->{'nombre'}) . "'" : 'ID ' . $module->{'id_agente'}) . ".", (defined ($agent) && $agent ne '' ? "'" . safe_output($agent->{'nombre'}) . "'" : 'ID ' . $module->{'id_agente'}) . ".",
10); 10);
# Ensure default values.
$module->{'min_ff_event'} = 0 unless defined($module->{'min_ff_event'});
$module->{'ff_timeout'} = 0 unless defined($module->{'ff_timeout'});
$module->{'module_interval'} = 0 unless defined($module->{'module_interval'});
if (ref($agent) eq 'HASH') {
if (!defined($agent->{'interval'}) && defined($agent->{'interval'})) {
$agent->{'intervalo'} = $agent->{'interval'};
}
}
# Get agent information # Get agent information
if (! defined ($agent) || $agent eq '') { if (! defined ($agent) || $agent eq '') {
@ -3134,6 +3147,8 @@ sub pandora_create_module_from_network_component ($$$$) {
pandora_create_module_tags ($pa_config, $dbh, $module_id, $component_tags); pandora_create_module_tags ($pa_config, $dbh, $module_id, $component_tags);
logger($pa_config, 'Creating module ' . safe_output ($component->{'nombre'}) . " (ID $module_id) for agent $addr from network component.", 10); logger($pa_config, 'Creating module ' . safe_output ($component->{'nombre'}) . " (ID $module_id) for agent $addr from network component.", 10);
return $module_id;
} }
########################################################################## ##########################################################################
@ -3141,7 +3156,7 @@ sub pandora_create_module_from_network_component ($$$$) {
########################################################################## ##########################################################################
sub pandora_create_module_from_hash ($$$) { sub pandora_create_module_from_hash ($$$) {
my ($pa_config, $parameters, $dbh) = @_; my ($pa_config, $parameters, $dbh) = @_;
logger($pa_config, logger($pa_config,
"Creating module '$parameters->{'nombre'}' for agent ID $parameters->{'id_agente'}.", 10); "Creating module '$parameters->{'nombre'}' for agent ID $parameters->{'id_agente'}.", 10);
@ -3172,8 +3187,12 @@ sub pandora_create_module_from_hash ($$$) {
} }
# Encrypt SNMP v3 passwords. # Encrypt SNMP v3 passwords.
if ($parameters->{'id_tipo_modulo'} >= 15 && $parameters->{'id_tipo_modulo'} <= 18 && if (defined($parameters->{'tcp_send'})
$parameters->{'tcp_send'} eq '3') { && $parameters->{'tcp_send'} eq '3'
&& defined($parameters->{'id_tipo_modulo'})
&& $parameters->{'id_tipo_modulo'} >= 15
&& $parameters->{'id_tipo_modulo'} <= 18
) {
$parameters->{'custom_string_2'} = pandora_input_password($pa_config, $parameters->{'custom_string_2'}); $parameters->{'custom_string_2'} = pandora_input_password($pa_config, $parameters->{'custom_string_2'});
} }
@ -3181,7 +3200,11 @@ sub pandora_create_module_from_hash ($$$) {
'tagente_modulo', $parameters); 'tagente_modulo', $parameters);
my $status = 4; my $status = 4;
if (defined ($parameters->{'id_tipo_modulo'}) && ($parameters->{'id_tipo_modulo'} == 21 || $parameters->{'id_tipo_modulo'} == 22 || $parameters->{'id_tipo_modulo'} == 23)) { if (defined ($parameters->{'id_tipo_modulo'})
&& ($parameters->{'id_tipo_modulo'} == 21
|| $parameters->{'id_tipo_modulo'} == 22
|| $parameters->{'id_tipo_modulo'} == 23)
) {
$status = 0; $status = 0;
} }
@ -3333,7 +3356,7 @@ sub pandora_create_agent ($$$$$$$$$$;$$$$$$$$$$) {
$agent_mode = 1 unless defined($agent_mode); $agent_mode = 1 unless defined($agent_mode);
$alias = $agent_name unless defined($alias); $alias = $agent_name unless defined($alias);
$description = "Created by $server_name" unless ($description ne ''); $description = "Created by $server_name" unless (defined($description) && $description ne '');
my ($columns, $values) = db_insert_get_values ({ 'nombre' => safe_input($agent_name), my ($columns, $values) = db_insert_get_values ({ 'nombre' => safe_input($agent_name),
'direccion' => $address, 'direccion' => $address,
'comentarios' => $description, 'comentarios' => $description,
@ -6295,6 +6318,63 @@ sub notification_set_targets {
return 1; return 1;
} }
##########################################################################
=head2 C<< notification_get_users (I<$dbh>, I<$source>) >>
Get targets for given sources
=cut
##########################################################################
sub notification_get_users {
my ($dbh, $source) = @_;
my @results = get_db_rows(
$dbh,
'SELECT id_user
FROM tnotification_source_user nsu
INNER JOIN tnotification_source ns ON nsu.id_source=ns.id
WHERE ns.description = ?
',
safe_input($source)
);
@results = map {
if(ref($_) eq 'HASH') { $_->{'id_user'} }
else {}
} @results;
return @results;
}
##########################################################################
=head2 C<< notification_get_groups (I<$dbh>, I<$source>) >>
Get targets for given sources
=cut
##########################################################################
sub notification_get_groups {
my ($dbh, $source) = @_;
my @results = get_db_rows(
$dbh,
'SELECT id_group
FROM tnotification_source_group nsg
INNER JOIN tnotification_source ns ON nsg.id_source=ns.id
WHERE ns.description = ?
',
safe_input($source)
);
@results = map {
if(ref($_) eq 'HASH') { $_->{'id_group'} }
else {}
} @results;
return @results;
}
# End of function declaration # End of function declaration
# End of defined Code # End of defined Code

View File

@ -20,6 +20,7 @@ package PandoraFMS::DB;
use strict; use strict;
use warnings; use warnings;
use DBI; use DBI;
use Carp qw/croak/;
use lib '/usr/lib/perl5'; use lib '/usr/lib/perl5';
use PandoraFMS::Tools; use PandoraFMS::Tools;
@ -80,6 +81,8 @@ our @EXPORT = qw(
get_module_id get_module_id
get_module_name get_module_name
get_nc_profile_name get_nc_profile_name
get_pen_templates
get_nc_profile_advanced
get_os_id get_os_id
get_os_name get_os_name
get_plugin_id get_plugin_id
@ -656,6 +659,48 @@ sub get_nc_profile_name ($$) {
return get_db_value ($dbh, "SELECT * FROM tnetwork_profile WHERE id_np = ?", $nc_id); return get_db_value ($dbh, "SELECT * FROM tnetwork_profile WHERE id_np = ?", $nc_id);
} }
##########################################################################
## Return all network component's profile ids matching given PEN.
##########################################################################
sub get_pen_templates($$) {
my ($dbh, $pen) = @_;
my @results = get_db_rows(
$dbh,
'SELECT t.`id_np`
FROM `tnetwork_profile` t
INNER JOIN `tnetwork_profile_pen` pp ON pp.`id_np` = t.`id_np`
INNER JOIN `tpen` p ON pp.pen = p.pen
WHERE p.`pen` = ?',
$pen
);
@results = map {
if (ref($_) eq 'HASH') { $_->{'id_np'} }
else {}
} @results;
return @results;
}
##########################################################################
## Return a network component's profile data and pen list, given its ID.
##########################################################################
sub get_nc_profile_advanced($$) {
my ($dbh, $id_nc) = @_;
return get_db_single_row(
$dbh,
'SELECT t.*,GROUP_CONCAT(p.pen) AS "pen"
FROM `tnetwork_profile` t
LEFT JOIN `tnetwork_profile_pen` pp ON t.id_np = pp.id_np
LEFT JOIN `tpen` p ON pp.pen = p.pen
WHERE t.`id_np` = ?
GROUP BY t.`id_np`',
$id_nc
);
}
########################################################################## ##########################################################################
## Return user profile ID given the user id, group id and profile id. ## Return user profile ID given the user id, group id and profile id.
########################################################################## ##########################################################################
@ -894,7 +939,7 @@ sub db_insert ($$$;@) {
$insert_id = $dbh->{'mysql_insertid'}; $insert_id = $dbh->{'mysql_insertid'};
} }
else { else {
die($exception); croak (join(', ', @_));
} }
} }
@ -917,7 +962,7 @@ sub db_update ($$;@) {
$rows = $dbh->do($query, undef, @values); $rows = $dbh->do($query, undef, @values);
} }
else { else {
die($exception); croak (join(', ', @_));
} }
} }
@ -1163,7 +1208,7 @@ sub db_do ($$;@) {
$dbh->do($query, undef, @values); $dbh->do($query, undef, @values);
} }
else { else {
die($exception); croak (join(', ', @_));
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -384,6 +384,7 @@ sub pandora_query_snmp ($$$$) {
my $output; # Command output my $output; # Command output
# If not defined, always snmp v1 (standard) # If not defined, always snmp v1 (standard)
$snmp_version = '1' unless defined($snmp_version);
if ($snmp_version ne '1' && $snmp_version ne '2' if ($snmp_version ne '1' && $snmp_version ne '2'
&& $snmp_version ne '2c' && $snmp_version ne '3') { && $snmp_version ne '2c' && $snmp_version ne '3') {
$snmp_version = '1'; $snmp_version = '1';
@ -470,7 +471,9 @@ sub exec_network_module ($$$$) {
my $retries = $module->{'max_retries'}; my $retries = $module->{'max_retries'};
my $target_os = pandora_get_os($dbh, $module->{'custom_string_2'}); my $target_os = pandora_get_os($dbh, $module->{'custom_string_2'});
if ($module->{'custom_string_2'} eq "inherited" ) { if (defined($module->{'custom_string_2'})
&& $module->{'custom_string_2'} eq "inherited"
) {
$target_os = $agent_row->{'id_os'}; $target_os = $agent_row->{'id_os'};
} elsif (!defined($target_os) || "$target_os" eq '0') { } elsif (!defined($target_os) || "$target_os" eq '0') {
$target_os = $agent_row->{'id_os'}; $target_os = $agent_row->{'id_os'};
@ -589,7 +592,7 @@ sub exec_network_module ($$$$) {
my %data = ("data" => $module_data); my %data = ("data" => $module_data);
pandora_process_module ($pa_config, \%data, '', $module, '', $timestamp, $utimestamp, $server_id, $dbh); pandora_process_module ($pa_config, \%data, '', $module, '', $timestamp, $utimestamp, $server_id, $dbh);
if ($agent_os_version eq ''){ if (!defined($agent_os_version) || $agent_os_version eq ''){
$agent_os_version = $pa_config->{'servername'}.'_Net'; $agent_os_version = $pa_config->{'servername'}.'_Net';
} }

View File

@ -33,7 +33,7 @@ our @ISA = qw(Exporter);
# version: Defines actual version of Pandora Server for this module only # version: Defines actual version of Pandora Server for this module only
my $pandora_version = "7.0NG.744"; my $pandora_version = "7.0NG.744";
my $pandora_build = "200413"; my $pandora_build = "200414";
our $VERSION = $pandora_version." ".$pandora_build; our $VERSION = $pandora_version." ".$pandora_build;
our %EXPORT_TAGS = ( 'all' => [ qw() ] ); our %EXPORT_TAGS = ( 'all' => [ qw() ] );

File diff suppressed because it is too large Load Diff

View File

@ -23,9 +23,9 @@ our @EXPORT = qw(
subnet_matches subnet_matches
); );
######################################################################################## ################################################################################
# Return an Enterprise Recon object. # Return an Enterprise Recon object.
######################################################################################## ################################################################################
sub enterprise_new($$) { sub enterprise_new($$) {
my ($class, $arguments) = @_; my ($class, $arguments) = @_;
@ -53,18 +53,18 @@ sub enterprise_new($$) {
} }
######################################################################################## ################################################################################
# Return the numeric representation of the given IP address. # Return the numeric representation of the given IP address.
######################################################################################## ################################################################################
sub ip_to_long($) { sub ip_to_long($) {
my $ip_address = shift; my $ip_address = shift;
return unpack('N', inet_aton($ip_address)); return unpack('N', inet_aton($ip_address));
} }
######################################################################################## ################################################################################
# Returns 1 if the two given MAC addresses are the same. # Returns 1 if the two given MAC addresses are the same.
######################################################################################## ################################################################################
sub mac_matches($$) { sub mac_matches($$) {
my ($mac_1, $mac_2) = @_; my ($mac_1, $mac_2) = @_;
@ -75,9 +75,9 @@ sub mac_matches($$) {
return 0; return 0;
} }
######################################################################################## ################################################################################
# Convert a MAC address to decimal dotted notation. # Convert a MAC address to decimal dotted notation.
######################################################################################## ################################################################################
sub mac_to_dec($) { sub mac_to_dec($) {
my $mac = shift; my $mac = shift;
@ -91,9 +91,9 @@ sub mac_to_dec($) {
return $dec_mac; return $dec_mac;
} }
######################################################################################## ################################################################################
# Make sure all MAC addresses are in the same format (00 11 22 33 44 55 66). # Make sure all MAC addresses are in the same format (00 11 22 33 44 55 66).
######################################################################################## ################################################################################
sub parse_mac($) { sub parse_mac($) {
my ($mac) = @_; my ($mac) = @_;
@ -114,9 +114,9 @@ sub parse_mac($) {
return $mac; return $mac;
} }
######################################################################################## ################################################################################
# Returns 1 if the given IP address belongs to the given subnet. # Returns 1 if the given IP address belongs to the given subnet.
######################################################################################## ################################################################################
sub subnet_matches($$;$) { sub subnet_matches($$;$) {
my ($ipaddr, $subnet, $mask) = @_; my ($ipaddr, $subnet, $mask) = @_;
my ($netaddr, $netmask); my ($netaddr, $netmask);

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_server %define name pandorafms_server
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
Summary: Pandora FMS Server Summary: Pandora FMS Server
Name: %{name} Name: %{name}

View File

@ -3,7 +3,7 @@
# #
%define name pandorafms_server %define name pandorafms_server
%define version 7.0NG.744 %define version 7.0NG.744
%define release 200413 %define release 200414
Summary: Pandora FMS Server Summary: Pandora FMS Server
Name: %{name} Name: %{name}

View File

@ -9,7 +9,7 @@
# ********************************************************************** # **********************************************************************
PI_VERSION="7.0NG.744" PI_VERSION="7.0NG.744"
PI_BUILD="200413" PI_BUILD="200414"
MODE=$1 MODE=$1
if [ $# -gt 1 ]; then if [ $# -gt 1 ]; then

View File

@ -35,7 +35,7 @@ use PandoraFMS::Config;
use PandoraFMS::DB; use PandoraFMS::DB;
# version: define current version # version: define current version
my $version = "7.0NG.744 PS200413"; my $version = "7.0NG.744 PS200414";
# Pandora server configuration # Pandora server configuration
my %conf; my %conf;

View File

@ -36,7 +36,7 @@ use Encode::Locale;
Encode::Locale::decode_argv; Encode::Locale::decode_argv;
# version: define current version # version: define current version
my $version = "7.0NG.744 PS200413"; my $version = "7.0NG.744 PS200414";
# save program name for logging # save program name for logging
my $progname = basename($0); my $progname = basename($0);

View File

@ -0,0 +1,308 @@
#!/usr/bin/perl
#
################################################################################
#
# SNMP wizard module
#
# Requirements:
# Net::SNMP
# Crypt::DES
# Digest::SHA1
#
# (c) Enrique Martin Garcia <enrique.martin@artica.es>
#
# 2020/03/10
#
################################################################################
use strict;
use warnings;
use POSIX qw(strftime);
use Encode;
use Encode::Locale;
use Getopt::Long;
use Net::SNMP;
my $HELP=<<EO_HELP;
Get the result of an arithmetic operation using several OIDs values.
Usage: $0 -host "<ip_address>" -version "<snmp_version>" [SNMP] [SNMPv3] -oidList "<oid1>,<oid2>" -operation "<aritmetic_operation>"
-host Target host
-version SNMP version (1, 2c, 3)
-oidList Comma separated OIDs used
-operation Aritmetic operation to get data.
Macros _oN_ will be changed by OIDs in list.
Example: (_o1_ * 100) / _o2_
[SNMP]
-community Community (only version 1 and 2c)
-port Target UDP port (Default 161)
[SNMPv3]
-user Username
-authMethod Authentication method (MD5, SHA)
-authPass Authentication password
-privMethod Privacy method (DES, AES)
-privPass Privacy password
-secLevel Security level (noAuthNoPriv, authNoPriv, authPriv)
Example: $0 -host 192.168.80.43 -community public -version 1 -oidlist "1.3.6.1.2.1.2.2.1.10.1,1.3.6.1.2.1.2.2.1.16.1" -operation "_o1_ + _o2_"
EO_HELP
#
# FUNCTIONS
##############
sub new_snmp_target {
my ($config) = @_;
my $target;
my $error;
if ($config->{'version'} ne '3'){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-community => $config->{'community'}
);
}else{
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'}
);
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'}
);
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'},
-privpassword => $config->{'priv_pass'},
-privprotocol => $config->{'priv_method'}
);
}
}
return ($target, $error);
}
sub snmp_walk {
my ($target, $oid) = @_;
my $result = {};
my $walk = $target->get_table(
-baseoid => $oid,
);
if (defined($walk)){
$result = $walk;
}
return $result;
}
sub snmp_get {
my ($target, $oid) = @_;
my $result = '';
my $get = $target->get_request(
-varbindlist => [$oid],
);
if (defined($get)){
$result = $get->{$oid};
}
return $result;
}
#
# MAIN
##############
@ARGV = map { decode(locale => $_, 1) } @ARGV if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
my %Param = ();
GetOptions(
\%Param,
# General
'community=s',
'version=s',
'host=s',
'port=s',
'timeout=s',
# Version 3
'user=s',
'authMethod=s',
'authPass=s',
'privMethod=s',
'privPass=s',
'secLevel=s',
# Operation
'oidList=s',
'operation=s',
# Help option
'Help',
);
if ($Param{Help}){
print $HELP;
exit 0;
}
my $config;
# General parameters
$config->{'community'} = $Param{community} || '';
$config->{'version'} = $Param{version} || '';
$config->{'host'} = $Param{host} || '';
$config->{'port'} = $Param{port} || '161';
$config->{'timeout'} = $Param{timeout} || '2';
# Version 3 parameters
$config->{'auth_method'} = $Param{authMethod} || '';
$config->{'user'} = $Param{user} || '';
$config->{'auth_pass'} = $Param{authPass} || '';
$config->{'priv_method'} = $Param{privMethod} || '';
$config->{'priv_pass'} = $Param{privPass} || '';
$config->{'sec_level'} = $Param{secLevel} || '';
$config->{'auth_method'} = uc($config->{'auth_method'});
$config->{'priv_method'} = uc($config->{'priv_method'});
# Operation
my $operation = $Param{operation} || '';
# OIDs
my @oid_list = split /,/, $Param{oidList} || '';
# Verify parameters
if (!$config->{'host'} || !$config->{'version'} || !$operation || !@oid_list){
print $HELP;
print "Host, version, OID list and operation are required.\n";
exit 1;
}
if ($config->{'version'} ne '1' && $config->{'version'} ne '2c' && $config->{'version'} ne '3'){
print $HELP;
print "Invalid SNMP version provided.\n";
exit 1;
}
if ($config->{'version'} eq '1' || $config->{'version'} eq '2c'){
if (!$config->{'community'}){
print $HELP;
print "SNMP community required for version 1 or 2c.\n";
exit 1;
}
}
if ($config->{'version'} eq '3'){
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
if (!$config->{'user'}){
print $HELP;
print "Username required for SNMP version 3 and security level 'noAuthNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'}){
print $HELP;
print "Username, authentication password and authentication method required for SNMP version 3 and security level 'authNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'} && !$config->{'priv_pass'} && !$config->{'priv_method'}){
print $HELP;
print "Username, authentication password, authentication method, privacy password and privacy method required for SNMP version 3 and security level 'authPriv'.\n";
exit 1;
}
}else{
print $HELP;
print "Invalid SNMP security level provided for version 3.\n";
exit 1;
}
if ($config->{'auth_method'} && $config->{'auth_method'} ne 'MD5' && $config->{'auth_method'} ne 'SHA'){
print $HELP;
print "Invalid SNMP authentication method provided for version 3.\n";
exit 1;
}
if ($config->{'priv_method'} && $config->{'priv_method'} ne 'DES' && $config->{'priv_method'} ne 'AES'){
print $HELP;
print "Invalid SNMP privacy method provided for version 3.\n";
exit 1;
}
}
# Verify operation (avoid code injection)
my @operation = split //, lc($operation);
foreach my $op (@operation){
if ($op !~ /\d/ && $op ne ' ' && $op ne '(' && $op ne ')' && $op ne '_' && $op ne '-' && $op ne '+' && $op ne '*' && $op ne '/' && $op ne 'o'){
print $HELP;
print "Specified operation has invalid characters: " . $op . "\n";
exit 1;
}
}
# Create SNMP target
my ($target, $error) = new_snmp_target($config);
if (!$target){
print $error . "\n";
exit 1;
}
# Get OIDs values
my $oid_values = {};
my $i = 1;
foreach my $oid (@oid_list){
$oid_values->{'_o' . $i . '_'} = snmp_get($target, $oid);
$i++;
}
# Change operation macros with values
$i = 1;
foreach my $k (keys %{$oid_values}){
my $oid_macro = '_o' . $i . '_';
my $value = $oid_values->{$oid_macro};
$operation =~ s/$oid_macro/$value/g;
$i++;
}
# Get operation result
my $result = eval $operation;
if (defined($result)){
print $result . "\n";
}

View File

@ -0,0 +1,282 @@
#!/usr/bin/perl
#
################################################################################
#
# SNMP wizard process
#
# Requirements:
# Net::SNMP
# Crypt::DES
# Digest::SHA1
#
# (c) Enrique Martin Garcia <enrique.martin@artica.es>
#
# 2020/03/10
#
################################################################################
use strict;
use warnings;
use POSIX qw(strftime);
use Encode;
use Encode::Locale;
use Getopt::Long;
use Net::SNMP;
my $HELP=<<EO_HELP;
Check if a process is running (1) or not (0) in OID .1.3.6.1.2.1.25.4.2.1.2 SNMP tree.
Usage: $0 -host "<ip_address>" -version "<snmp_version>" [SNMP] [SNMPv3] -process "<process_name>"
-host Target host
-version SNMP version (1, 2c, 3)
-process Process name to check if is running (case sensitive)
[SNMP]
-community Community (only version 1 and 2c)
-port Target UDP port (Default 161)
[SNMPv3]
-user Username
-authMethod Authentication method (MD5, SHA)
-authPass Authentication password
-privMethod Privacy method (DES, AES)
-privPass Privacy password
-secLevel Security level (noAuthNoPriv, authNoPriv, authPriv)
Example: $0 -host 192.168.80.43 -community public -version 1 -process "httpd"
EO_HELP
#
# FUNCTIONS
##############
sub new_snmp_target {
my ($config) = @_;
my $target;
my $error;
if ($config->{'version'} ne '3'){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-community => $config->{'community'}
);
}else{
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'}
);
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'}
);
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'},
-privpassword => $config->{'priv_pass'},
-privprotocol => $config->{'priv_method'}
);
}
}
return ($target, $error);
}
sub snmp_walk {
my ($target, $oid) = @_;
my $result = {};
my $walk = $target->get_table(
-baseoid => $oid,
);
if (defined($walk)){
$result = $walk;
}
return $result;
}
sub snmp_get {
my ($target, $oid) = @_;
my $result = '';
my $get = $target->get_request(
-varbindlist => [$oid],
);
if (defined($get)){
$result = $get->{$oid};
}
return $result;
}
#
# MAIN
##############
@ARGV = map { decode(locale => $_, 1) } @ARGV if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
my %Param = ();
GetOptions(
\%Param,
# General
'community=s',
'version=s',
'host=s',
'port=s',
'timeout=s',
# Version 3
'user=s',
'authMethod=s',
'authPass=s',
'privMethod=s',
'privPass=s',
'secLevel=s',
# Process
'process=s',
# Help option
'Help',
);
if ($Param{Help}){
print $HELP;
exit 0;
}
my $config;
# General parameters
$config->{'community'} = $Param{community} || '';
$config->{'version'} = $Param{version} || '';
$config->{'host'} = $Param{host} || '';
$config->{'port'} = $Param{port} || '161';
$config->{'timeout'} = $Param{timeout} || '2';
# Version 3 parameters
$config->{'auth_method'} = $Param{authMethod} || '';
$config->{'user'} = $Param{user} || '';
$config->{'auth_pass'} = $Param{authPass} || '';
$config->{'priv_method'} = $Param{privMethod} || '';
$config->{'priv_pass'} = $Param{privPass} || '';
$config->{'sec_level'} = $Param{secLevel} || '';
$config->{'auth_method'} = uc($config->{'auth_method'});
$config->{'priv_method'} = uc($config->{'priv_method'});
# Operation
my $process = $Param{process} || '';
# Verify parameters
if (!$config->{'host'} || !$config->{'version'} || !$process){
print $HELP;
print "Host, version and process are required.\n";
exit 1;
}
if ($config->{'version'} ne '1' && $config->{'version'} ne '2c' && $config->{'version'} ne '3'){
print $HELP;
print "Invalid SNMP version provided.\n";
exit 1;
}
if ($config->{'version'} eq '1' || $config->{'version'} eq '2c'){
if (!$config->{'community'}){
print $HELP;
print "SNMP community required for version 1 or 2c.\n";
exit 1;
}
}
if ($config->{'version'} eq '3'){
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
if (!$config->{'user'}){
print $HELP;
print "Username required for SNMP version 3 and security level 'noAuthNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'}){
print $HELP;
print "Username, authentication password and authentication method required for SNMP version 3 and security level 'authNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'} && !$config->{'priv_pass'} && !$config->{'priv_method'}){
print $HELP;
print "Username, authentication password, authentication method, privacy password and privacy method required for SNMP version 3 and security level 'authPriv'.\n";
exit 1;
}
}else{
print $HELP;
print "Invalid SNMP security level provided for version 3.\n";
exit 1;
}
if ($config->{'auth_method'} && $config->{'auth_method'} ne 'MD5' && $config->{'auth_method'} ne 'SHA'){
print $HELP;
print "Invalid SNMP authentication method provided for version 3.\n";
exit 1;
}
if ($config->{'priv_method'} && $config->{'priv_method'} ne 'DES' && $config->{'priv_method'} ne 'AES'){
print $HELP;
print "Invalid SNMP privacy method provided for version 3.\n";
exit 1;
}
}
# Create SNMP target
my ($target, $error) = new_snmp_target($config);
if (!$target){
print $error . "\n";
exit 1;
}
# Get all running processes
my $processes = snmp_walk($target, '.1.3.6.1.2.1.25.4.2.1.2');
my $result = 0;
# Search process name
foreach my $k (keys %{$processes}){
if ($processes->{$k} eq $process){
$result = 1;
last;
}
}
print $result . "\n";

View File

@ -0,0 +1,176 @@
#!/usr/bin/perl
#
################################################################################
#
# WMI wizard module
#
# Requirements:
# wmic
#
# (c) Enrique Martin Garcia <enrique.martin@artica.es>
#
# 2020/03/10
#
################################################################################
use strict;
use warnings;
use POSIX qw(strftime);
use Encode;
use Encode::Locale;
use Getopt::Long;
use Data::Dumper;
my $HELP=<<EO_HELP;
Get the result of an arithmetic operation using distinct fields in a WMI query (Query must return only 1 row).
Usage: $0 [-wmicPath "<path_to_wmic>"] -host "<ip_address>" [-namespace "<namespace>"] -user "<username>" -pass "<password>" -wmiClass "<wmi_class>" -fieldsList "<class_fields_names>" [-queryFilter "<query_filter>"] -operation "<aritmetic_operation>"
-wmicPath Path to wmic command (Default: /usr/bin/wmic)
-host Target host
-namespace WMI namespace
-user Windows username ([domain/]username)
-pass User password
-wmiClass WMI class for query (Example: Win32_OperatingSystem)
-fieldsList Comma separated class fields list (Example: TotalVisibleMemorySize,FreePhysicalMemory)
-queryFilter WMI query class filter (Example: DeviceID = 3 AND DeviceType = 1)
-operation Aritmetic operation to get data.
Macros _fN_ will be changed by fields in list.
Example: ((_f1_ - _f2_) * 100) / _f1_
Example: $0 -host "192.168.80.43" -user "pandora/Administrator" -pass "PandoraFMS1234" -wmiClass "Win32_OperatingSystem" -fieldsList "TotalVisibleMemorySize,FreePhysicalMemory" -operation "((_f1_ - _f2_) * 100) / _f1_"
EO_HELP
#
# MAIN
##############
@ARGV = map { decode(locale => $_, 1) } @ARGV if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
my %Param = ();
GetOptions(
\%Param,
# General
'wmicPath=s',
'host=s',
'namespace=s',
'user=s',
'pass=s',
# Query
'wmiClass=s',
'fieldsList=s',
'queryFilter=s',
# Operation
'operation=s',
# Help option
'Help',
);
if ($Param{Help}){
print $HELP;
exit 0;
}
my $config;
# General parameters
$config->{'wmicPath'} = $Param{wmicPath} || '/usr/bin/wmic';
$config->{'host'} = $Param{host} || '';
$config->{'namespace'} = $Param{namespace} || '';
$config->{'user'} = $Param{user} || '';
$config->{'pass'} = $Param{pass} || '';
# Query parameters
$config->{'wmiClass'} = $Param{wmiClass} || '';
$config->{'queryFilter'} = $Param{queryFilter} || '';
$config->{'fieldsList'} = $Param{fieldsList} || '';
# Operation
my $operation = $Param{operation} || '';
# Fields
my @fields_list = split /,/, $config->{'fieldsList'} || '';
# Verify parameters
if (!$config->{'host'} || !$config->{'user'} || !$config->{'pass'} || !$config->{'wmiClass'} || !@fields_list || !$operation){
print $HELP;
print "Host, user, password, WMI class, fields list and operation are required.\n";
exit 1;
}
# Verify operation (avoid code injection)
my @operation = split //, lc($operation);
foreach my $op (@operation){
if ($op !~ /\d/ && $op ne ' ' && $op ne '(' && $op ne ')' && $op ne '_' && $op ne '-' && $op ne '+' && $op ne '*' && $op ne '/' && $op ne 'f'){
print $HELP;
print "Specified operation has invalid characters: " . $op . "\n";
exit 1;
}
}
# Build WMI query
my $wmi_query = 'SELECT ' . $config->{'fieldsList'} . ' FROM ' . $config->{'wmiClass'} . ($config->{'queryFilter'} ? ' WHERE ' . $config->{'queryFilter'} : '');
# Build wmic command
my $wmi_command = $config->{'wmicPath'} . ' -U ' . $config->{'user'} . '%' . $config->{'pass'} . ($config->{'namespace'} ? ' --namespace="' . $config->{'namespace'} . '"' : '') . ' //' . $config->{'host'} . ' "' . $wmi_query . '"';
# Run wmic and parse output
my $output = `$wmi_command 2>/dev/null`;
my @data = split("\n", $output);
if ($data[0] ne 'CLASS: ' . $config->{'wmiClass'}){
print $output;
exit 1;
}
# Parse fields positions
my @fields_pos;
my $i = 0;
foreach my $field (split /\|/, $data[1]){
my $x = 1;
foreach my $f (@fields_list){
$f =~ s/^\s*//;
$f =~ s/\s*$//;
if (lc($field) eq lc($f)){
$fields_pos[$i] = $x;
}
$x++;
}
$i++;
}
# Get fields values
my $fields_values = {};
$i = 0;
foreach my $field_value (split /\|/, $data[2]){
$fields_values->{'_f' . $fields_pos[$i] . '_'} = $field_value;
$i++;
}
# Change operation macros with values
$i = 1;
foreach my $k (keys %{$fields_values}){
my $field_macro = '_f' . $i . '_';
my $value = $fields_values->{$field_macro};
$operation =~ s/$field_macro/$value/g;
$i++;
}
# Get operation result
my $result = eval $operation;
if (defined($result)){
print $result . "\n";
}