mise à jour ansible glpi

This commit is contained in:
lucas.dubief
2022-02-11 15:48:06 +01:00
parent 3bae0bc39a
commit 9ddd78ea91
1017 changed files with 394347 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
deny from all
</IfModule>

View File

@@ -0,0 +1,310 @@
#!/usr/bin/php
<?php
// Drop unused files from the internal repository.
//
// This script should be called periodically via cron. Especially if you
// synchronize multiple repositories.
//
// /<path to plugin fusioninventory>/scripts/cleanup_repository.php
$doc = <<<DOC
cleanup_repository.php
Usage:
cleanup_repository.php [-n] [-h | -q | -d ]
-h, --help show this help
-q, --quiet run quietly
-d, --debug display more execution messages
-n, --dry-run just show what will be done
DOC;
error_reporting( E_ALL );
ini_set("display_errors", 'stderr');
ini_set("log_errors", true);
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include ("../../../inc/includes.php");
include ("./docopt.php");
require ("./logging.php");
define ( 'MANIFESTS_PATH',
implode(
DIRECTORY_SEPARATOR,
[ GLPI_PLUGIN_DOC_DIR, 'fusioninventory', 'files' , 'manifests' ]
)
);
define ( 'REPOSITORY_PATH',
implode(
DIRECTORY_SEPARATOR,
[ GLPI_PLUGIN_DOC_DIR, 'fusioninventory', 'files', 'repository' ]
)
);
class MyRecursiveFilterIterator extends RecursiveFilterIterator {
public function accept() {
return !preg_match('/^\./', $this->current()->getFilename());
}
}
/**
* Get every files used at least by one package.
*/
function getManifestsUsed($logger) {
global $DB;
$result = [];
$orders = $DB->request('glpi_plugin_fusioninventory_deployorders');
foreach ($orders as $order_data) {
$logger->debug(" Get Files from Order ID ". $order_data['id']);
$order_config = json_decode($order_data['json']);
if (isset($order_config->jobs)
&& isset($order_config->jobs->associatedFiles)
&& count($order_config->jobs->associatedFiles) > 0) {
foreach ($order_config->jobs->associatedFiles as $manifest) {
$logger->debug($manifest);
if (!in_array($manifest, $result)) {
$result[] = $manifest;
}
}
}
}
return $result;
}
/**
* Get every files used at least by one package.
*/
function getManifestsRegistered($logger) {
global $DB;
$result = [];
$files = $DB->request('glpi_plugin_fusioninventory_deployfiles');
foreach ($files as $file_data) {
$logger->debug(" Get File ID ". $file_data['id']);
$logger->debug($file_data);
if (!in_array($file_data['sha512'], $result)) {
$result[] = $file_data['sha512'];
}
}
return $result;
}
/**
* Get the manifest files list in the repository.
*/
function getManifests($logger) {
$result = [];
$manifests = new DirectoryIterator( MANIFESTS_PATH );
foreach ($manifests as $manifest) {
if ($manifest->isFile()) {
$logger->debug( $manifest->getFilename() );
$result[] = $manifest->getFilename();
}
}
return $result;
}
/**
* Remove invalid manifests from repository.
* This will remove the fileparts from repository
*/
function removeInvalidManifests($logger, $dryrun, $invalid_manifests, $valid_manifests) {
$logger->info("Removing ".count($invalid_manifests)." invalid manifests");
$invalid_fileparts = [];
foreach ($invalid_manifests as $manifest) {
$filepath = implode( DIRECTORY_SEPARATOR, [MANIFESTS_PATH,$manifest] );
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
while (($buffer = fgets($file)) !== false) {
$buffer = trim($buffer);
if (!in_array($buffer, $invalid_fileparts)) {
$invalid_fileparts[] = $buffer;
}
}
fclose($file);
}
}
//Excluding valid fileparts shared with invalid fileparts.
foreach ($valid_manifests as $manifest) {
$filepath = implode( DIRECTORY_SEPARATOR, [MANIFESTS_PATH,$manifest] );
//No need to process the file if it doesn't exist.
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
while (($buffer = fgets($file)) !== false) {
$buffer = trim($buffer);
// Exclude the valid filepart from invalid list if it exists in the latter.
if (($index = array_search($buffer, $invalid_fileparts)) !== false) {
unset( $invalid_fileparts[$index] );
}
}
fclose($file);
}
}
/**
* Removing fileparts
*/
$logger->info( count($invalid_fileparts) . " resulting invalid fileparts from manifests.");
$fileparts_repository = new RecursiveDirectoryIterator( REPOSITORY_PATH );
$fileparts_iterator = new RecursiveIteratorIterator($fileparts_repository);
$total = 0;
foreach ($fileparts_iterator as $filepart) {
if ($filepart->isFile() && in_array($filepart->getFilename(), $invalid_fileparts)) {
$logger->debug( "Start removing " . $filepart->getFileName() .".");
if (!$dryrun) {
$logger->debug( "Removing " . $filepart->getPathName() .".");
unlink($filepart->getPathName());
$total += 1;
} else {
$logger->debug( "Will remove " . $filepart->getPathName() .".");
}
}
}
$logger->info( $total . " fileparts have been removed.");
}
/**
* Unregister the invalid manifests from database.
*/
function unregisterInvalidManifests($logger, $dryrun, $invalid_manifests) {
$logger->info("Unregistering ".count($invalid_manifests)." manifests from database.");
$pfDeployFile = new PluginFusioninventoryDeployFile();
foreach ($invalid_manifests as $manifest) {
$short_sha512 = substr($manifest, 0, 6);
$data = $pfDeployFile->find(['shortsha512' => $short_sha512]);
foreach ($data as $config) {
$pfDeployFile->getFromDB($config['id']);
$logger->info("Unregister file " . $pfDeployFile->fields['name']);
if (!$dryrun) {
$pfDeployFile->deleteFromDB();
}
}
}
}
/**
* Process arguments passed to the script
*/
$docopt = new \Docopt\Handler();
$args = $docopt->handle($doc);
$loglevel = Logging::$LOG_INFO;
$dryrun = $args['--dry-run'];
if ($args['--quiet']) {
$loglevel = Logging::$LOG_QUIET;
} else if ($args['--debug']) {
$loglevel = Logging::$LOG_DEBUG;
} else {
$loglevel = Logging::$LOG_INFO;
}
$logger = new Logging($loglevel);
/**
* Just do some debug with arguments scanned by docopt
*/
$logger->debug( "Script " . $_SERVER['argv'][0] . "called with following arguments:");
foreach ($args as $k=>$v) {
$logger->debug( $k.': '.json_encode($v));
}
/**
* Get every manifests in use in packages
*/
$manifests_used = getManifestsUsed($logger);
$logger->info(count($manifests_used) . " manifest(s) used in packages.");
$logger->debug($manifests_used);
/**
* Get every manifests registered in database
*/
$manifests_registered = getManifestsRegistered($logger);
$logger->info( count($manifests_registered) . " manifest(s) registered in database.");
$logger->debug($manifests_registered);
/**
* Get every manifests stored in the repository
*/
$manifests = getManifests($logger);
$logger->info( count($manifests). " manifest(s) in repository.");
$logger->debug($manifests);
/**
* Get invalid registered manifests in database (ie. those manifests are no longer in use in any
* packages).
*/
$invalid_manifests = array_diff($manifests_registered, $manifests_used);
$logger->info( count($invalid_manifests) . " invalid manifest(s).");
$logger->debug($invalid_manifests );
/**
* Get valid registered manifests in database (ie. still in use by packages).
*/
$valid_manifests = array_diff($manifests_registered, $invalid_manifests);
$logger->info( count($valid_manifests) . " valid manifest(s).");
$logger->debug($valid_manifests );
removeInvalidManifests($logger, $dryrun, $invalid_manifests, $valid_manifests);
unregisterInvalidManifests($logger, $dryrun, $invalid_manifests);
$logger->info( 'Memory used : ' .number_format(memory_get_usage(true)/1024/1024, 3) . 'MiB');
$logger->info( 'Memory used (emalloc): ' .number_format(memory_get_usage()/1024/1024, 3) . 'MiB');

View File

@@ -0,0 +1,45 @@
<?php
/*
------------------------------------------------------------------------
FusionInventory
Copyright (C) 2010-2016 by the FusionInventory Development Team.
http://www.fusioninventory.org/ http://forge.fusioninventory.org/
------------------------------------------------------------------------
LICENSE
This file is part of FusionInventory project.
FusionInventory is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FusionInventory 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
@package FusionInventory
@author David Durieux
@co-author
@copyright Copyright (c) 2010-2016 FusionInventory team
@license AGPL License 3.0 or (at your option) any later version
http://www.gnu.org/licenses/agpl-3.0-standalone.html
@link http://www.fusioninventory.org/
@link http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
@since 2010
------------------------------------------------------------------------
*/
echo "Use glpi console:\n";
echo " * php bin/console glpi:plugin:install --username=glpi fusioninventory\n";
echo " * php bin/console glpi:plugin:activate fusioninventory\n";

View File

@@ -0,0 +1,88 @@
#!/usr/bin/php
<?php
// Generate snmpwalk of unknown devices
// requires: snmpwalk from Net-SNMP
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include ("../../../inc/includes.php");
$snmpwalkCmd = "snmpwalk";
// $snmpwalkCmd = "ssh 192.168.14.128 --";
// you can launch snmpwalk on a remote machine through ssh:
// tunnel="0",command="/usr/bin/snmpwalk $SSH_ORIGINAL_COMMAND" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0FqlGjmx6IxuPihc1B1zN1gTnGZoQs1SenUaRkmUD+gbUWbfhUBbPRJIIFicNjsr6toerAQM/YKfZnmYG5BnYKgJPbKdkpdrSTMwSUqccDFH8tu6lIoRFiqZgajIznUls3Mhz5B4JXErapbQN/7cWnpvuG8vdZu56N19T0/gYdlTf8a71liva20zBk+y+pdWWsd4l2zBLm6tkmMWqYL/Xj/jY92gLzY0Dm0IFiBfV9gk4UBWh6jycLBZGbdqx25XqK8L8Ob9oyhJhtsCNeft1c6xzNAM21WYH4/trtwYgHaEA1LLN4IbY9+lJfJamN9ii4acyfMz/J+lQsnw3yTlOw== root@mysnmpmachine
$outputDir = GLPI_PLUGIN_DOC_DIR.'/fusioninventory/walk';
if (mkdir($outputDir) && !is_dir($outputDir)) {
echo("Failed to create $outputDir\n");
exit(1);
}
$t = system(sprintf("%s --version", $snmpwalkCmd));
if (!strncmp("/NET-SNMP/", $t, 7)) {
echo "[error] snmpwalk not found. please install snmpwalk from Net-SNMP package\n";
exit(1);
}
$sql = "
SELECT
DISTINCT(ip),sysdescr,snmpversion,community
FROM
glpi_plugin_fusinvsnmp_unmanageds,
glpi_networkports,
glpi_plugin_fusioninventory_configsecurities
WHERE
glpi_plugin_fusinvsnmp_unmanageds.plugin_fusioninventory_snmpmodels_id<1
AND
sysdescr IS NOT NULL
AND
glpi_networkports.itemtype='PluginFusioninventoryUnmanaged'
AND
glpi_networkports.items_id=plugin_fusioninventory_unmanageds_id
AND
length(glpi_networkports.ip)>1
AND
glpi_plugin_fusioninventory_configsecurities.id=glpi_plugin_fusinvsnmp_unmanageds.plugin_fusinvsnmp_configsecurities_id
";
$result = $DB->query($sql);
while ($host=$DB->fetchArray($result)) {
$filePath = sprintf("%s/%s-%s.walk", $outputDir, $host['ip'], preg_replace('/[^a-zA-Z0-9,_-]/', '_', $host['sysdescr']));
switch ($host['snmpversion']) {
case 1:
$snmpversion = '1';
break;
case 2:
$snmpversion = '2c';
break;
default:
printf("unsupported SNMP version: '%s'\n", $host['snmpversion']);
continue;
}
$cmd = sprintf("%s -v %s -t 30 -Cc -c %s %s .1", $snmpwalkCmd, $snmpversion, $host['community'], $host['ip']);
// print $cmd."\n";
printf("---\nscanning %s\n", $host['ip']);
$fileFd = fopen($filePath, "w");
$cmdFd = popen($cmd, "r");
while (!feof($cmdFd)) {
fwrite($fileFd, fgets($cmdFd));
}
print "done\n";
pclose($cmdFd);
fclose($fileFd);
$st = stat($filePath);
if ($st['size'] == 0) {
unlink($filePath);
} else {
printf("file %s generated\n", $filePath);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
#!/usr/bin/php
<?php
$doc = <<<DOC
get_agent_jobs.php
Usage:
get_agent_jobs.php [-h | -q | -d ] [--methods=methods] [<device_ids>...]
-h, --help show this help
-q, --quiet run quietly
-d, --debug display more execution messages
device_ids the agent's device_ids registered in GLPI
DOC;
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include ("../../../inc/includes.php");
include ("./docopt.php");
require ("./logging.php");
/**
* Process arguments passed to the script
*/
$docopt = new \Docopt\Handler();
$args = $docopt->handle($doc);
$logger = new Logging();
$logger->setLevelFromArgs($args['--quiet'], $args['--debug']);
$logger->debug($args);
$agent = new PluginFusioninventoryAgent();
$computer = new Computer();
$task = new PluginFusioninventoryTask();
$staticmisc_methods = PluginFusioninventoryStaticmisc::getmethods();
$methods = [];
foreach ($staticmisc_methods as $method) {
$methods[$method['method']] = $method['method'];
}
$device_ids = [];
if (count($args['<device_ids>']) == 0) {
$agents = array_values($agent->find());
$randid = rand(0, count($agents));
$device_ids = [$agents[$randid]['device_id']];
} else {
$device_ids = $args['<device_ids>'];
}
//$logger->debug($device_ids);
foreach ($device_ids as $device_id) {
$logger->info("Get prepared jobs for Agent '$device_id'");
// $jobstates = $task->getTaskjobstatesForAgent($device_id, $methods, array('read_only'=>true));
// $jobstates = $task->getTaskjobstatesForAgent($device_id, $methods);
$time = microtime(true);
file_get_contents("http://glpi.kroy-laptop.sandbox/glpi/plugins/fusioninventory/b/deploy/?action=getJobs&machineid=".$device_id);
$time = microtime(true) - $time;
$logger->info("Get prepared jobs for Agent '$device_id' : $time s");
}

View File

@@ -0,0 +1,44 @@
#!/usr/bin/php
<?php
$doc = <<<DOC
get_job_logs.php
Usage:
get_job_logs.php [-h | -q | -d ] [-m methods] [-t task_ids]
-h, --help Show this help
-q, --quiet Run quietly
-d, --debug Show informations.
-m, --methods=methods Show only tasks defined with a list of methods (separated by commas).
-t, --tasks=task_ids Filter logs by tasks (separated by commas)
DOC;
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include ("../../../inc/includes.php");
include ("./docopt.php");
require ("./logging.php");
/**
* Process arguments passed to the script
*/
$docopt = new \Docopt\Handler();
$args = $docopt->handle($doc);
$logger = new Logging();
$logger->setLevelFromArgs($args['--quiet'], $args['--debug']);
$logger->debug($args);
/*
* Get Running Tasks
*/
$pfTask = new PluginFusioninventoryTask();
$logs = $pfTask->getJoblogs();
$logger->info($logs);

View File

@@ -0,0 +1,4 @@
Nom Entité Début de la plage IP Fin de la plage IP Authentification SNMP
IP range 1 Racine > Sous entité 2 192.168.0.1 192.168.0.254 Public community v2c
IP range 2 Racine > Sous entité 1 > Sous entité 1.1 192.168.1.1 192.168.1.128 Public community v1
IP range 3 Racine > Sous entité 1 > Sous entité 1.2 10.6.50.1 10.6.50.254 Public community v1 Public community v2c
1 Nom Entité Début de la plage IP Fin de la plage IP Authentification SNMP
2 IP range 1 Racine > Sous entité 2 192.168.0.1 192.168.0.254 Public community v2c
3 IP range 2 Racine > Sous entité 1 > Sous entité 1.1 192.168.1.1 192.168.1.128 Public community v1
4 IP range 3 Racine > Sous entité 1 > Sous entité 1.2 10.6.50.1 10.6.50.254 Public community v1 Public community v2c

View File

@@ -0,0 +1,274 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the agents
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Frédéric Mohier
* @copyright Copyright (c) 2010-2017 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
include ("../../../inc/includes.php");
$db_cfg_sec = new PluginFusioninventoryConfigSecurity();
$db_ip_range = new PluginFusioninventoryIPRange();
$db_ip_range_snmp = new PluginFusioninventoryIPRange_ConfigSecurity();
$db_agent = new PluginFusioninventoryAgent();
$db_entity = new Entity();
$file = './import_ip_ranges.csv';
// CVS default file format
$DELIMITER = "\t";
$ENCLOSURE = '"';
/**
* Script for importing SNMP credentials into the GLPI Fusion Inventory
* - search and open a CSV file
* - import found IP ranges and relations with SNMP credentials
*/
$row = 1;
if (($handle = fopen($file, "r")) !== false) {
while (($data = fgetcsv($handle, 0, $DELIMITER, $ENCLOSURE)) !== false) {
$data[0] = trim($data[0]);
if (strtolower($data[0]) == 'nom') {
// File header
echo "File header: " . serialize($data) . "\n";
continue;
}
// Check fields count
if (count($data) < 4) {
// Skip empty line...
echo "-> skipping empty line!\n";
continue;
}
// Clean name field
$name = trim($data[0]);
if ($name == '') {
// Skip empty name...
echo "-> skipping empty name!\n";
continue;
}
// echo "Data: " . serialize($data) . "\n";
echo "\n-----\nNew IP range: $name:\n";
// Clean and check Entity field
$entity = trim($data[1]);
if ($entity != '') {
$db_entities = $db_entity->find(['completename' => $entity], [], 1);
if (count($db_entities) > 0) {
$found_entity = current($db_entities);
$entity_id = $found_entity["id"];
echo "-> found " . count($db_entities) . " matching entity: " . $found_entity["completename"] . "\n";
} else {
echo "-> skipping not found entity: '$name / $entity'!\n";
continue;
}
}
// Clean and check range start
$range_start = trim($data[2]);
if ($range_start == '' OR (! check_valid_ip($range_start))) {
// Skip invalid data...
echo "-> skipping empty or invalid IP range start: '$name / $range_start'!\n";
continue;
}
// Clean and check range stop
$range_stop = trim($data[3]);
if ($range_stop == '' OR (! check_valid_ip($range_stop))) {
// Skip invalid data...
echo "-> skipping empty or invalid IP range stop: '$name / $range_stop'!\n";
continue;
}
echo "-> IP range from: $range_start to $range_stop\n";
// Clean and check SNMP credentials fields
$i = 4;
$ar_snmp_auth = [];
while ($i < count($data)) {
$snmp_auth = trim($data[$i]);
if ($snmp_auth != '') {
$snmp_auths = $db_cfg_sec->find("`name`='".$snmp_auth."'", '', 1);
if (count($snmp_auths) > 0) {
$snmp = current($snmp_auths);
echo "-> found " . count($snmp_auths) . " matching SNMP credentials: " . $snmp["name"] . "\n";
array_push($ar_snmp_auth, $snmp["id"]);
} else {
echo "-> skipping missing SNMP credentials: '$name / $snmp_auth'!\n";
continue;
}
} else {
// No SNMP credentials for this IP range
echo "-> empty SNMP credentials: '$name'!\n";
}
$i++;
}
/* If some more SNMP credentials are needed...
// Clean and check SNMP credentials field #2
$snmp_auth = trim($data[4]);
if ($snmp_auth != '') {
$snmp_auths = $db_cfg_sec->find(['name' => $snmp_auth], [], 1);
if (count($snmp_auths) > 0) {
$snmp = current($snmp_auths);
$snmp_auth = $snmp["id"];
echo "-> found " . count($snmp_auths) . " matching SNMP credentials: " . $snmp["name"] . "\n";
} else {
echo "-> skipping missing SNMP credentials: '$name / $snmp_auth'!\n";
continue;
}
}
if ($snmp_auth == '') {
$snmp_auth = 0;
}
$snmp_auth2 = $snmp_auth;
// Clean and check SNMP credentials field #3
$snmp_auth = trim($data[5]);
if ($snmp_auth != '') {
$snmp_auths = $db_cfg_sec->find(['name' => $snmp_auth], [], 1);
if (count($snmp_auths) > 0) {
$snmp = current($snmp_auths);
$snmp_auth = $snmp["id"];
echo "-> found " . count($snmp_auths) . " matching SNMP credentials: " . $snmp["name"] . "\n";
} else {
echo "-> skipping missing SNMP credentials: '$name / $snmp_auth'!\n";
continue;
}
}
if ($snmp_auth == '') {
$snmp_auth = 0;
}
$snmp_auth3 = $snmp_auth;
*/
/*
* Now we have all the fields to create a new IP range
*/
$input = [
'name' => $name,
'entities_id' => $entity_id,
'ip_start' => $range_start,
'ip_end' => $range_stop
];
$ipranges_id = -1;
$ipranges = $db_ip_range->find(['name' => $name], [], 1);
if (count($ipranges) > 0) {
// Update an existing IP range
$range = current($ipranges);
$ipranges_id = $range["id"];
$input['id'] = $ipranges_id;
echo "-> updating an existing IP addresses range: '$name'...";
$db_ip_range->update($input);
echo " updated.\n";
} else {
// Create a new IP range
echo "-> creating a new IP addresses range: '$name'...";
$ipranges_id = $db_ip_range->add($input);
if (! $ipranges_id) {
echo " error when adding an IP range!\n";
print_r($input);
} else {
echo " created.\n";
}
}
foreach ($ar_snmp_auth as $snmp_auth_id) {
// Relation between IP range and SNMP credentials (if it exists...)
$input = [
'plugin_fusioninventory_ipranges_id' => $ipranges_id,
'plugin_fusioninventory_configsecurities_id' => $snmp_auth_id
];
if ($ipranges_id != -1) {
$ipranges_snmp = $db_ip_range_snmp->find(['plugin_fusioninventory_ipranges_id' => $ipranges_id]);
if (count($ipranges_snmp) > 0) {
if ($snmp_auth_id == -1) {
echo "-> deleting an existing IP addresses range / SNMP credentials relation...";
$range_snmp = current($ipranges_snmp);
$db_ip_range_snmp->getFromDB($range_snmp['id']);
$db_ip_range_snmp->deleteFromDB();
echo " deleted.\n";
continue;
} else {
// Update an existing IP range / SNMP relation
$range_snmp = current($ipranges_snmp);
$input['id'] = $range_snmp["id"];
echo "-> updating an existing IP addresses range / SNMP credentials relation...";
$db_ip_range_snmp->update($input);
echo " updated.\n";
}
} else {
if ($snmp_auth_id != -1) {
// Create a new IP range / SNMP relation
echo "-> creating a new IP addresses range / SNMP credentials relation...";
$ipranges_snmp_id = $db_ip_range_snmp->add($input);
if (! $ipranges_snmp_id) {
echo " error when adding an IP range / SNMP relation!\n";
print_r($input);
} else {
echo " created.\n";
}
}
}
}
}
}
fclose($handle);
}
function check_valid_ip($ip_address) {
$valid_address = true;
$ip_fields = explode(".", $ip_address);
if (count($ip_fields) < 4) {
return false;
}
foreach ($ip_fields as $ip_field) {
if (!is_numeric($ip_field) OR $ip_field > 255) {
$valid_address = false;
break;
}
}
return $valid_address;
}

View File

@@ -0,0 +1,63 @@
Le script import_ip_ranges.php permet d'importer et/ou de mettre à jour la table des plages d'adresses IP du
plugin FusionInventory ainsi que les relations entre les plages d'adresse IP et l'authentification SNMP à utiliser.
Ce script lit le contenu d'un fichier au format CSV pour réaliser l'importation. Ce fichier doit être formatté de
la façon suivante:
Nom;Entité;Début de la plage IP;Fin de la plage IP;Authentification SNMP
AdmConsoles_NT 240/24;Racine > Réseau ESU;10.107.240.1;10.107.240.200;WAN
AdmConsoles_NT 242/24;Racine > Réseau ESU;10.107.240.2;10.107.240.201;Passerelle
AdmDMZ11_NT;Racine > Réseau ESU;10.107.240.3;10.107.240.202;Passerelle
host-BRU_A-WanX;Racine > Etranger > Crasic Bruxelles ;10.107.240.4 ;10.107.240.203 ;Passerelle
host-BRU_D-WanX;Racine > Etranger > Crasic Bruxelles ;10.107.240.5 ;10.107.240.204 ;Passerelle
host-BRU_RO-WanX;Racine > Etranger > Crasic Bruxelles ;10.107.240.6 ;10.107.240.205 ;Passerelle
host-WAS_A-WanX;Racine > Etranger > Crasic Washington ;10.107.240.7 ;10.107.240.206 ;Passerelle
host-WAS_R-WanX;Racine > Etranger > Crasic Washington ;10.107.240.8 ;10.107.240.207 ;Passerelle
net-BRU_A-Vlan1400;Racine > Etranger > Crasic Bruxelles ;10.107.240.9 ;10.107.240.208 ;Passerelle
net-BRU_A-Vlan50;Racine > Etranger > Crasic Bruxelles ;10.107.240.10 ;10.107.240.209 ;Passerelle
net-BRU_D-Vlan1400;Racine > Etranger > Crasic Bruxelles ;10.107.240.11 ;10.107.240.210 ;WAN
net-BRU_D-Vlan50-1;Racine > Etranger > Crasic Bruxelles ;10.107.240.12 ;10.107.240.211 ;WAN
net-BRU_D-Vlan50-2;Racine > Etranger > Crasic Bruxelles ;10.107.240.13 ;10.107.240.212 ;WAN
net-BRU_RO-Vlan1400;Racine > Etranger > Crasic Bruxelles ;10.107.240.14 ;10.107.240.213 ;WAN
net-BRU_RO-Vlan50;Racine > Etranger > Crasic Bruxelles ;10.107.240.15 ;10.107.240.214 ;WAN
net-WAS_A-Vlan1400;Racine > Etranger > Crasic Washington ;10.107.240.16 ;10.107.240.215 ;WAN
net-WAS_A-Vlan50-1;Racine > Etranger > Crasic Washington ;10.107.240.17 ;10.107.240.216 ;WAN
net-WAS_A-Vlan50-2;Racine > Etranger > Crasic Washington ;10.107.240.18 ;10.107.240.217 ;WAN
net-WAS_A-Vlan50-3;Racine > Etranger > Crasic Washington ;10.107.240.19 ;10.107.240.218 ;WAN
net-WAS_A-Vlan50-4; Racine > Etranger > Crasic Washington ;10.107.240.20 ;10.107.240.219 ;WAN
net-WAS_R-Vlan1400; Racine > Etranger > Crasic Washington ;10.107.240.21 ;10.107.240.220 ;WAN
net-WAS_R-Vlan50; Racine > Etranger > Crasic Washington ;10.107.240.22 ;10.107.240.221 ;WAN
- chaque ligne doit contenir au moins 4 champs qui sont séparés par le caractère ; (point-virgule)
- le contenu d'un champ peut être entoure de " (double quotes) s'il contient un ;
- une ligne qui ne contient pas au moins 4 champs sera ignorée
- une ligne d'entête peut exister, elle sera ignoré par le script et ne sera pas importée. Cette ligne d'entête
est détectée par le fait que le premier champ sur la ligne lu contient "Nom"
- chaque ligne contient:
- le nom de la plage d'adresses
- le nom complet l'entité de rattachement. Il s'agit du chemin de l'entité depuis l'entité racine incluse, donc
Racine > Sous entité > Sous sous entité. Chaque élement est séparé par " > "
- le début de la page d'adresses
- la fin de la plage d'adresses
- le nom de l'authentification SNMP liée à la plage d'adresses (optionnel)
- les 4 premiers champs sont obligatoires alors que l'authentification SNMP est facultative
- le script vérifie les points suivants :
- l'entité existe dans la base de données
- l'adresse de début de la plage est une bien une adresse IP valide
- l'adresse de fin de la plage est une bien une adresse IP valide
- l'authentification SNMP existe dans la base de données
- si une des vérifications échoue, la ligne concernée n'est pas importée.
- l'import d'une ligne va créer une nouvelle plage d'adresses IP dans la base de données ou mettre à jour une
plage d'adresses existante si un élément de même nom est trouvé dans la base de données. De ce fait, le script
permet la création de nouvelles plages d'adresses et il peut être rejoué plusieurs fois pour réaliser la mise
à jour des plages d'adresses déjà importées
- si une authentification SNMP est indiquée dans la ligne, la relation entre la plage d'adresses IP et
l'authentification SNMP va être créée ou mise à jour si elle existe déjà
- si aucune authentification SNMP n'est indiquée dans la ligne, et qu'il existe une relation entre la plage d'adresses IP et
une authentification SNMP, cette relation va être supprimée

View File

@@ -0,0 +1,100 @@
<?php
/**
* Logging facility
*/
ini_set("log_errors", true);
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
set_error_handler(null);
include_once(__DIR__ . "/../../../inc/toolbox.class.php");
class Logging {
public static $LOG_CRITICAL = ['level'=>50, 'name'=>'CRITICAL '];
public static $LOG_ERROR = ['level'=>40, 'name'=>'ERROR '];
public static $LOG_QUIET = ['level'=>35, 'name'=>'QUIET '];
public static $LOG_WARNING = ['level'=>30, 'name'=>'WARNING '];
public static $LOG_INFO = ['level'=>20, 'name'=>'INFO '];
public static $LOG_DEBUG = ['level'=>10, 'name'=>'DEBUG '];
public $loglevel;
public function __construct($loglevel = null) {
if (is_null($loglevel)) {
$this->loglevel = self::$LOG_INFO;
} else {
$this->loglevel = $loglevel;
}
}
public function formatlog($messages, $loglevel) {
$msg = [];
foreach ($messages as $message) {
if (is_array($message) || is_object($message)) {
//$msg[] = print_r($message, true);
$msg[] = PluginFusioninventoryToolbox::formatJson(json_encode($message));
} else if (is_null($message)) {
$msg[] = ' NULL';
} else if (is_bool($message)) {
$msg[] = ($message ? 'true' : 'false');
} else {
$msg[] = $message;
}
}
return $loglevel['name'] . ': '. implode("\n", $msg);
}
function printlog($msg = "", $loglevel = null) {
if (is_null($loglevel)) {
$loglevel = self::$LOG_INFO;
}
/*
print(
var_export($this->loglevel['level'],true) . " >= " .
var_export($loglevel['level'],true) . "\n"
);
*/
if ($this->loglevel['level'] <= $loglevel['level']) {
print( $this->formatlog($msg, $loglevel) . PHP_EOL );
}
}
function info() {
$msg = func_get_args();
$this->printlog($msg, self::$LOG_INFO);
}
function error() {
$msg = func_get_args();
$this->printlog($msg, self::$LOG_ERROR);
}
function debug() {
$msg = func_get_args();
$this->printlog($msg, self::$LOG_DEBUG);
}
function setLevelFromArgs($quiet = false, $debug = false) {
$this->loglevel = self::$LOG_INFO;
if ($quiet) {
$this->loglevel = self::$LOG_QUIET;
} else if ($debug) {
$this->loglevel = self::$LOG_DEBUG;
}
}
}

View File

@@ -0,0 +1,38 @@
#!/usr/bin/php
<?php
$doc = <<<DOC
prepare_jobs.php
Usage:
prepare_jobs.php [-h | -q | -d ]
-h, --help show this help
-q, --quiet run quietly
-d, --debug display more execution messages
DOC;
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include ("../../../inc/includes.php");
include ("./docopt.php");
require ("./logging.php");
$_SESSION["glpicronuserrunning"] = 1;
/**
* Process arguments passed to the script
*/
$docopt = new \Docopt\Handler();
$args = $docopt->handle($doc);
$logger = new Logging();
$logger->setLevelFromArgs($args['--quiet'], $args['--debug']);
$task = new PluginFusioninventoryTask();
$task->cronTaskscheduler();