function discover_new_device($hostname, $source = 'xdp') { global $config, $debug; if ($config['autodiscovery'][$source]) { echo "Discovering new host {$hostname}\n"; if (!empty($config['mydomain']) && isDomainResolves($hostname . "." . $config['mydomain'])) { if ($debug) { echo "appending " . $config['mydomain'] . "!\n"; } $dst_host = $hostname . "." . $config['mydomain']; } else { $dst_host = $hostname; } $ip = gethostbyname($dst_host); if ($debug) { echo "resolving {$dst_host} to {$ip}\n"; } if (match_network($config['autodiscovery']['ip_nets'], $ip)) { if ($debug) { echo "found {$ip} inside configured nets, adding!\n"; } $remote_device_id = addHost($dst_host); if ($remote_device_id) { $remote_device = device_by_id_cache($remote_device_id, 1); array_push($GLOBALS['devices'], $remote_device); return $remote_device_id; } } } else { if ($debug) { echo "{$source} autodiscovery disabled"; } return FALSE; } }
function discover_new_device($hostname, $device = '', $method = '', $interface = '') { global $config; if (!empty($config['mydomain']) && isDomainResolves($hostname . '.' . $config['mydomain'])) { $dst_host = $hostname . '.' . $config['mydomain']; } else { $dst_host = $hostname; } d_echo("discovering {$dst_host}\n"); $ip = gethostbyname($dst_host); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { // $ip isn't a valid IP so it must be a name. if ($ip == $dst_host) { d_echo("name lookup of {$dst_host} failed\n"); log_event("{$method} discovery of " . $dst_host . " failed - Check name lookup", $device['device_id'], 'discovery'); return false; } } elseif (filter_var($dst_host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === true || filter_var($dst_host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === true) { // gethostbyname returned a valid $ip, was $dst_host an IP? if ($config['discovery_by_ip'] === false) { d_echo('Discovery by IP disabled, skipping ' . $dst_host); log_event("{$method} discovery of " . $dst_host . " failed - Discovery by IP disabled", $device['device_id'], 'discovery'); return false; } } d_echo("ip lookup result: {$ip}\n"); $dst_host = rtrim($dst_host, '.'); // remove trailing dot if (match_network($config['autodiscovery']['nets-exclude'], $ip)) { d_echo("{$ip} in an excluded network - skipping\n"); return false; } if (match_network($config['nets'], $ip)) { try { $remote_device_id = addHost($dst_host, '', '161', 'udp', $config['distributed_poller_group']); $remote_device = device_by_id_cache($remote_device_id, 1); echo '+[' . $remote_device['hostname'] . '(' . $remote_device['device_id'] . ')]'; discover_device($remote_device); device_by_id_cache($remote_device_id, 1); if ($remote_device_id && is_array($device) && !empty($method)) { $extra_log = ''; $int = ifNameDescr($interface); if (is_array($int)) { $extra_log = ' (port ' . $int['label'] . ') '; } log_event('Device ' . $remote_device['hostname'] . " ({$ip}) {$extra_log} autodiscovered through {$method} on " . $device['hostname'], $remote_device_id, 'discovery'); } else { log_event("{$method} discovery of " . $remote_device['hostname'] . " ({$ip}) failed - Check ping and SNMP access", $device['device_id'], 'discovery'); } return $remote_device_id; } catch (HostExistsException $e) { // already have this device } catch (Exception $e) { log_event("{$method} discovery of " . $dst_host . " ({$ip}) failed - " . $e->getMessage()); } } else { d_echo("{$ip} not in a matched network - skipping\n"); } //end if }
function discover_new_device($hostname, $device = '', $method = '', $interface = '') { global $config, $debug; if (!empty($config['mydomain']) && isDomainResolves($hostname . '.' . $config['mydomain'])) { $dst_host = $hostname . '.' . $config['mydomain']; } else { $dst_host = $hostname; } if ($debug) { echo "discovering {$dst_host}\n"; } $ip = gethostbyname($dst_host); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { // $ip isn't a valid IP so it must be a name. if ($ip == $dst_host) { if ($debug) { echo "name lookup of {$dst_host} failed\n"; } return false; } } if ($debug) { echo "ip lookup result: {$ip}\n"; } $dst_host = rtrim($dst_host, '.'); // remove trailing dot if (match_network($config['autodiscovery']['nets-exclude'], $ip)) { if ($debug) { echo "{$ip} in an excluded network - skipping\n"; } return false; } if (match_network($config['nets'], $ip)) { $remote_device_id = addHost($dst_host, '', '161', 'udp', '0', $config['distributed_poller_group']); if ($remote_device_id) { $remote_device = device_by_id_cache($remote_device_id, 1); echo '+[' . $remote_device['hostname'] . '(' . $remote_device['device_id'] . ')]'; discover_device($remote_device); device_by_id_cache($remote_device_id, 1); if ($remote_device_id && is_array($device) && !empty($method)) { $extra_log = ''; $int = ifNameDescr($interface); if (is_array($int)) { $extra_log = ' (port ' . $int['label'] . ') '; } log_event('Device $' . $remote_device['hostname'] . " ({$ip}) {$extra_log} autodiscovered through {$method} on " . $device['hostname'], $remote_device_id, 'system'); } else { log_event("{$method} discovery of " . $remote_device['hostname'] . " ({$ip}) failed - check ping and SNMP access", $device['device_id'], 'system'); } return $remote_device_id; } } else { if ($debug) { echo "{$ip} not in a matched network - skipping\n"; } } //end if }
function perform_snmp_scan($net) { global $stats, $config, $debug, $vdebug; echo 'Range: ' . $net->network . '/' . $net->bitmask . PHP_EOL; $config['snmp']['timeout'] = 1; $config['snmp']['retries'] = 0; $config['fping_options']['retries'] = 0; $start = ip2long($net->network); $end = ip2long($net->broadcast) - 1; while ($start++ < $end) { $stats['count']++; $host = long2ip($start); if (match_network($config['autodiscovery']['nets-exclude'], $host)) { echo '|'; continue; } $test = isPingable($host); if ($test['result'] === false) { echo '.'; continue; } if (ip_exists($host)) { $stats['known']++; echo '*'; continue; } foreach (array('udp', 'tcp') as $transport) { try { addHost(gethostbyaddr($host), '', $config['snmp']['port'], $transport, $config['distributed_poller_group']); $stats['added']++; echo '+'; break; } catch (HostExistsException $e) { $stats['known']++; echo '*'; break; } catch (HostUnreachablePingException $e) { echo '.'; break; } catch (HostUnreachableException $e) { if ($debug) { print_error($e->getMessage() . " over {$transport}"); foreach ($e->getReasons() as $reason) { echo " {$reason}\n"; } } if ($transport == 'tcp') { // tried both udp and tcp without success $stats['failed']++; echo '-'; } } } } echo PHP_EOL; }
function discover_new_device($hostname) { global $config, $debug; if ($config['autodiscovery']['xdp']) { if (isDomainResolves($hostname . "." . $config['mydomain'])) { $dst_host = $hostname . "." . $config['mydomain']; } else { $dst_host = $hostname; } if ($debug) { echo "discovering {$dst_host}\n"; } $ip = gethostbyname($dst_host); if ($ip == $dst_host) { if ($debug) { echo "name lookup of {$dst_host} failed\n"; } return FALSE; } else { if ($debug) { echo "ip lookup result: {$ip}\n"; } } $dst_host = rtrim($dst_host, '.'); // remove trailing dot if (match_network($config['autodiscovery']['nets-exclude'], $ip)) { if ($debug) { echo "{$ip} in an excluded network - skipping\n"; } return FALSE; } if (match_network($config['nets'], $ip)) { $remote_device_id = addHost($dst_host); if ($remote_device_id) { $remote_device = device_by_id_cache($remote_device_id, 1); echo "+[" . $remote_device['hostname'] . "(" . $remote_device['device_id'] . ")]"; discover_device($remote_device); $remote_device = device_by_id_cache($remote_device_id, 1); return $remote_device_id; } } else { if ($debug) { echo "{$ip} not in a matched network - skipping\n"; } } } else { if ($debug) { echo "autodiscovery disabled - skipping\n"; } return FALSE; } }
function discover_new_device($hostname) { global $config, $debug; if (!empty($config['mydomain']) && isDomainResolves($hostname . "." . $config['mydomain'])) { $dst_host = $hostname . "." . $config['mydomain']; } else { $dst_host = $hostname; } if ($debug) { echo "discovering {$dst_host}\n"; } $ip = gethostbyname($dst_host); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE) { // $ip isn't a valid IP so it must be a name. if ($ip == $dst_host) { if ($debug) { echo "name lookup of {$dst_host} failed\n"; } return FALSE; } } if ($debug) { echo "ip lookup result: {$ip}\n"; } $dst_host = rtrim($dst_host, '.'); // remove trailing dot if (match_network($config['autodiscovery']['nets-exclude'], $ip)) { if ($debug) { echo "{$ip} in an excluded network - skipping\n"; } return FALSE; } if (match_network($config['nets'], $ip)) { $remote_device_id = addHost($dst_host, '', '161', 'udp', '0', $config['distributed_poller_group']); if ($remote_device_id) { $remote_device = device_by_id_cache($remote_device_id, 1); echo "+[" . $remote_device['hostname'] . "(" . $remote_device['device_id'] . ")]"; discover_device($remote_device); device_by_id_cache($remote_device_id, 1); return $remote_device_id; } } else { if ($debug) { echo "{$ip} not in a matched network - skipping\n"; } } }
function perform_snmp_scan($net) { global $stats, $config, $quiet; echo 'Range: ' . $net->network . '/' . $net->bitmask . PHP_EOL; $config['snmp']['timeout'] = 1; $config['snmp']['retries'] = 0; $config['fping_options']['retries'] = 0; $start = ip2long($net->network); $end = ip2long($net->broadcast) - 1; while ($start++ < $end) { $stats['count']++; $device_id = false; $host = long2ip($start); $test = isPingable($host); if ($test['result'] === false) { echo '.'; continue; } if (ip_exists($host)) { $stats['known']++; echo '*'; continue; } foreach (array('udp', 'tcp') as $transport) { if ($device_id !== false && $device_id > 0) { $stats['added']++; echo '+'; } else { if ($device_id === 0) { $stats['failed']++; echo '-'; break; } } $device_id = addHost(gethostbyaddr($host), '', $config['snmp']['port'], $transport, $quiet, $config['distributed_poller_group'], 0); } } echo PHP_EOL; }
function addLotOfObjects() { $taglist = genericAssertion('taglist', 'array0'); assertUIntArg('global_type_id', TRUE); assertStringArg('namelist', TRUE); $global_type_id = $_REQUEST['global_type_id']; if ($global_type_id == 0 or !strlen($_REQUEST['namelist'])) { showError('Incomplete form has been ignored. Cheers.'); return; } else { // The name extractor below was stolen from ophandlers.php:addMultiPorts() $names1 = explode("\n", $_REQUEST['namelist']); $names2 = array(); foreach ($names1 as $line) { $parts = explode('\\r', $line); reset($parts); if (!strlen($parts[0])) { continue; } else { $names2[] = rtrim($parts[0]); } } foreach ($names2 as $name) { try { $object_id = commitAddObject($name, NULL, $global_type_id, '', $taglist); $info = spotEntity('object', $object_id); amplifyCell($info); ############################################################################################### # add zabbix host $result = addHost($info['dname']); if (isset($result['error'])) { showError('Adding zabbix host is failed. Error message:' . $result['error']); } # END ############################################################################################### showSuccess("added object " . formatPortLink($info['id'], $info['dname'], NULL, NULL)); } catch (RackTablesError $e) { showError("Error creating object '{$name}': " . $e->getMessage()); continue; } } } }
// parse all remaining args if (is_numeric($arg)) { $port = $arg; } elseif (preg_match('/(' . implode('|', $config['snmp']['transports']) . ')/i', $arg)) { $transport = $arg; } elseif (preg_match('/^(v1|v2c)$/i', $arg)) { $snmpver = $arg; } } if ($community) { $config['snmp']['community'] = array($community); } } //end if try { $device_id = addHost($host, $snmpver, $port, $transport, $poller_group, $force_add, $port_assoc_mode); $device = device_by_id_cache($device_id); echo "Added device {$device['hostname']} ({$device_id})\n"; exit(0); } catch (HostUnreachableException $e) { print_error($e->getMessage()); foreach ($e->getReasons() as $reason) { echo " {$reason}\n"; } exit(2); } catch (Exception $e) { print_error($e->getMessage()); exit(3); } } else { c_echo("\n" . $config['project_name_version'] . ' Add Host Tool
array_push($config['snmp']['v3'], $v3); $snmpver = 'v3'; print_message("Adding SNMPv3 host {$hostname} port {$port}"); } else { print_error('Unsupported SNMP Version. There was a dropdown menu, how did you reach this error ?'); } } //end if $poller_group = $_POST['poller_group']; $force_add = $_POST['force_add']; if ($force_add == 'on') { $force_add = 1; } else { $force_add = 0; } $result = addHost($hostname, $snmpver, $port, $transport, 0, $poller_group, $force_add); if ($result) { print_message("Device added ({$result})"); } } else { print_error("You don't have the necessary privileges to add hosts."); } //end if echo ' </div> <div class="col-sm-3"> </div> </div>'; } //end if $pagetitle[] = 'Add host'; ?>
function perform_snmp_scan($net, $force_network, $force_broadcast) { global $stats, $config, $debug, $vdebug; echo 'Range: ' . $net->network . '/' . $net->bitmask . PHP_EOL; $config['snmp']['timeout'] = 1; $config['snmp']['retries'] = 0; $config['fping_options']['retries'] = 0; $start = ip2long($net->network); $end = ip2long($net->broadcast) - 1; if ($force_network === true) { //Force-scan network address d_echo("Forcing network address scan" . PHP_EOL); $start = $start - 1; } if ($force_broadcast === true) { //Force-scan broadcast address d_echo("Forcing broadcast address scan" . PHP_EOL); $end = $end + 1; } if ($net->bitmask === "31") { //Handle RFC3021 /31 prefixes $start = ip2long($net->network) - 1; $end = ip2long($net->broadcast); d_echo("RFC3021 network, hosts " . long2ip($start + 1) . " and " . long2ip($end) . PHP_EOL . PHP_EOL); } elseif ($net->bitmask === "32") { //Handle single-host /32 prefixes $start = ip2long($net->network) - 1; $end = $start + 1; d_echo("RFC3021 network, hosts " . long2ip($start + 1) . " and " . long2ip($end) . PHP_EOL . PHP_EOL); } else { d_echo("Network: " . $net->network . PHP_EOL); d_echo("Broadcast: " . $net->broadcast . PHP_EOL . PHP_EOL); } while ($start++ < $end) { $stats['count']++; $host = long2ip($start); if ($vdebug) { echo "Scanning: " . $host . PHP_EOL; } if (match_network($config['autodiscovery']['nets-exclude'], $host)) { if ($vdebug) { echo "Excluded by config.php" . PHP_EOL . PHP_EOL; } else { echo '|'; } continue; } $test = isPingable($host); if ($test['result'] === false) { if ($vdebug) { echo "Unpingable Device" . PHP_EOL . PHP_EOL; } else { echo '.'; } continue; } if (ip_exists($host)) { $stats['known']++; if ($vdebug) { echo "Known Device" . PHP_EOL; } else { echo '*'; } continue; } foreach (array('udp', 'tcp') as $transport) { try { addHost(gethostbyaddr($host), '', $config['snmp']['port'], $transport, $config['distributed_poller_group']); $stats['added']++; if ($vdebug) { echo "Added Device" . PHP_EOL . PHP_EOL; } else { echo '+'; } break; } catch (HostExistsException $e) { $stats['known']++; if ($vdebug) { echo "Known Device" . PHP_EOL . PHP_EOL; } else { echo '*'; } break; } catch (HostUnreachablePingException $e) { if ($vdebug) { echo "Unpingable Device" . PHP_EOL . PHP_EOL; } else { echo '.'; } break; } catch (HostUnreachableException $e) { if ($debug) { print_error($e->getMessage() . " over {$transport}"); foreach ($e->getReasons() as $reason) { echo " {$reason}" . PHP_EOL; } } if ($transport === 'tcp') { // tried both udp and tcp without success $stats['failed']++; if ($vdebug) { echo "Failed to Add Device" . PHP_EOL . PHP_EOL; } else { echo '-'; } } } } } echo PHP_EOL; }
#!/usr/bin/php <?php include "includes/defaults.inc.php"; include "config.php"; include "includes/functions.php"; $search = $argv[1] . "\$"; $data = trim(`cat ips-scanned.txt | grep alive | cut -d" " -f 1 | egrep {$search}`); foreach (explode("\n", $data) as $ip) { $snmp = shell_exec("snmpget -t 0.2 -v2c -c " . $config['community'] . " {$ip} sysName.0"); if (strstr($snmp, "STRING")) { $hostname = trim(str_replace("SNMPv2-MIB::sysName.0 = STRING: ", "", $snmp)); if (mysql_result(mysql_query("SELECT COUNT(device_id) FROM devices WHERE hostname = '{$hostname}'"), 0) == '0') { if (gethostbyname($hostname) == gethostbyname($hostname . "." . $config['mydomain'])) { $hostname = $hostname . "." . $config['mydomain']; } addHost($hostname, $community, 'v2c'); echo "Adding {$hostname} \n"; } } }
while ($arg = array_shift($v2args)) { // parse all remaining args if (is_numeric($arg)) { $port = $arg; } elseif (preg_match('/(' . implode("|", $config['snmp']['transports']) . ')/i', $arg)) { $transport = $arg; } elseif (preg_match('/^(v1|v2c)$/i', $arg)) { $snmpver = $arg; } } if ($community) { $config['snmp']['community'] = array($community); } $device_id = addHost($host, $snmpver, $port, $transport); } if ($snmpver) { $snmpversions[] = $snmpver; } else { $snmpversions = array('v2c', 'v3', 'v1'); } while (!$device_id && count($snmpversions)) { $snmpver = array_shift($snmpversions); $device_id = addHost($host, $snmpver, $port, $transport); } if ($device_id) { $device = device_by_id_cache($device_id); echo "Added device " . $device['hostname'] . " (" . $device_id . ")\n"; exit; } } print Console_Color::convert("\n" . $config['project_name_version'] . " Add Host Tool\n\nUsage (SNMPv1/2c): ./addhost.php <%Whostname%n> [community] [v1|v2c] [port] [" . implode("|", $config['snmp']['transports']) . "]\nUsage (SNMPv3) : Config Defaults : ./addhost.php <%Whostname%n> any v3 [user] [port] [" . implode("|", $config['snmp']['transports']) . "]\n No Auth, No Priv : ./addhost.php <%Whostname%n> nanp v3 [user] [port] [" . implode("|", $config['snmp']['transports']) . "]\n Auth, No Priv : ./addhost.php <%Whostname%n> anp v3 <user> <password> [md5|sha] [port] [" . implode("|", $config['snmp']['transports']) . "]\n Auth, Priv : ./addhost.php <%Whostname%n> ap v3 <user> <password> <enckey> [md5|sha] [aes|dsa] [port] [" . implode("|", $config['snmp']['transports']) . "]\n%rRemember to run discovery for the host afterwards.%n\n\n");
function addHost($host, $snmpver, $port = '161', $transport = 'udp', $quiet = '0', $poller_group = '0', $force_add = '0') { global $config; list($hostshort) = explode(".", $host); // Test Database Exists if (dbFetchCell("SELECT COUNT(*) FROM `devices` WHERE `hostname` = ?", array($host)) == '0') { if ($config['addhost_alwayscheckip'] === TRUE) { $ip = gethostbyname($host); } else { $ip = $host; } if (ip_exists($ip) === false) { // Test reachability if ($force_add == 1 || isPingable($host)) { if (empty($snmpver)) { // Try SNMPv2c $snmpver = 'v2c'; $ret = addHost($host, $snmpver, $port, $transport, $quiet, $poller_group, $force_add); if (!$ret) { //Try SNMPv3 $snmpver = 'v3'; $ret = addHost($host, $snmpver, $port, $transport, $quiet, $poller_group, $force_add); if (!$ret) { // Try SNMPv1 $snmpver = 'v1'; return addHost($host, $snmpver, $port, $transport, $quiet, $poller_group, $force_add); } else { return $ret; } } else { return $ret; } } if ($snmpver === "v3") { // Try each set of parameters from config foreach ($config['snmp']['v3'] as $v3) { $device = deviceArray($host, NULL, $snmpver, $port, $transport, $v3); if ($quiet == '0') { print_message("Trying v3 parameters " . $v3['authname'] . "/" . $v3['authlevel'] . " ... "); } if ($force_add == 1 || isSNMPable($device)) { $snmphost = snmp_get($device, "sysName.0", "-Oqv", "SNMPv2-MIB"); if (empty($snmphost) or $snmphost == $host || ($hostshort = $host)) { $device_id = createHost($host, NULL, $snmpver, $port, $transport, $v3, $poller_group); return $device_id; } else { if ($quiet == '0') { print_error("Given hostname does not match SNMP-read hostname ({$snmphost})!"); } } } else { if ($quiet == '0') { print_error("No reply on credentials " . $v3['authname'] . "/" . $v3['authlevel'] . " using {$snmpver}"); } } } } elseif ($snmpver === "v2c" or $snmpver === "v1") { // try each community from config foreach ($config['snmp']['community'] as $community) { $device = deviceArray($host, $community, $snmpver, $port, $transport, NULL); if ($quiet == '0') { print_message("Trying community {$community} ..."); } if ($force_add == 1 || isSNMPable($device)) { $snmphost = snmp_get($device, "sysName.0", "-Oqv", "SNMPv2-MIB"); if (empty($snmphost) || $snmphost && ($snmphost == $host || ($hostshort = $host))) { $device_id = createHost($host, $community, $snmpver, $port, $transport, array(), $poller_group); return $device_id; } else { if ($quiet == '0') { print_error("Given hostname does not match SNMP-read hostname ({$snmphost})!"); } } } else { if ($quiet == '0') { print_error("No reply on community {$community} using {$snmpver}"); } } } } else { if ($quiet == '0') { print_error("Unsupported SNMP Version \"{$snmpver}\"."); } } if (!$device_id) { // Failed SNMP if ($quiet == '0') { print_error("Could not reach {$host} with given SNMP community using {$snmpver}"); } } } else { // failed Reachability if ($quiet == '0') { print_error("Could not ping {$host}"); } } } else { if ($quiet == 0) { print_error("Already have host with this IP {$host}"); } } } else { // found in database if ($quiet == '0') { print_error("Already got host {$host}"); } } return 0; }
} print_message("Adding host {$hostname} communit" . (count($config['snmp']['community']) == 1 ? "y" : "ies") . " " . implode(', ', $config['snmp']['community']) . " port {$port}"); } elseif ($_POST['snmpver'] === "v3") { $v3 = array('authlevel' => mres($_POST['authlevel']), 'authname' => mres($_POST['authname']), 'authpass' => mres($_POST['authpass']), 'authalgo' => mres($_POST['authalgo']), 'cryptopass' => mres($_POST['cryptopass']), 'cryptoalgo' => mres($_POST['cryptoalgo'])); array_push($config['snmp']['v3'], $v3); $snmpver = "v3"; if ($_POST['port']) { $port = mres($_POST['port']); } else { $port = "161"; } print_message("Adding SNMPv3 host {$hostname} port {$port}"); } else { print_error("Unsupported SNMP Version. There was a dropdown menu, how did you reach this error ?"); } $result = addHost($hostname, $snmpver, $port); if ($result) { print_message("Device added ({$result})"); } } else { print_error("You don't have the necessary privileges to add hosts."); } } $pagetitle[] = "Add host"; ?> <form name="form1" method="post" action="" class="form-horizontal"> <p>Devices will be checked for Ping and SNMP reachability before being probed. Only devices with recognised OSes will be added.</p> <fieldset>
} } if ($community) { $config['snmp']['community'] = array($community); } $device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add); } //end if if ($snmpver) { $snmpversions[] = $snmpver; } else { $snmpversions = array('v2c', 'v3', 'v1'); } while (!$device_id && count($snmpversions)) { $snmpver = array_shift($snmpversions); $device_id = addHost($host, $snmpver, $port, $transport, 0, $poller_group, $force_add); } if ($device_id) { $device = device_by_id_cache($device_id); echo 'Added device ' . $device['hostname'] . ' (' . $device_id . ")\n"; exit; } } //end if print $console_color->convert("\n" . $config['project_name_version'] . ' Add Host Tool Usage (SNMPv1/2c): ./addhost.php [-g <poller group>] [-f] <%Whostname%n> [community] [v1|v2c] [port] [' . implode('|', $config['snmp']['transports']) . '] Usage (SNMPv3) : Config Defaults : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> any v3 [user] [port] [' . implode('|', $config['snmp']['transports']) . '] No Auth, No Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> nanp v3 [user] [port] [' . implode('|', $config['snmp']['transports']) . '] Auth, No Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> anp v3 <user> <password> [md5|sha] [port] [' . implode('|', $config['snmp']['transports']) . '] Auth, Priv : ./addhost.php [-g <poller group>] [-f]<%Whostname%n> ap v3 <user> <password> <enckey> [md5|sha] [aes|dsa] [port] [' . implode('|', $config['snmp']['transports']) . ']
exit; } echo "<h2>Add Device</h2>"; if ($_POST['hostname'] && $_POST['community']) { if ($_SESSION['userlevel'] > '5') { $hostname = mres($_POST['hostname']); $community = mres($_POST['community']); $snmpver = mres($_POST['snmpver']); if ($_POST['port']) { $port = mres($_POST['port']); } else { $port = "161"; } echo "<p class='messagebox'>"; echo "Adding host {$hostname} community {$community} port {$port}</p>"; $result = addHost($hostname, $community, $snmpver, $port); echo "</p>"; } else { echo "<p class='errorbox'><b>Error:</b> You don't have the necessary privileges to add hosts.</p>"; } } elseif ($_POST['hostname'] && !$_POST['community']) { echo "<p class='errorbox'><b>Error:</b> A community string is required.</p>"; } elseif (!$_POST['hostname'] && $_POST['community']) { echo "<p class='errorbox'><b>Error:</b> A hostname is required.</p>"; } ?> <form name="form1" method="post" action="<?php echo $config['base_url']; ?> /addhost/">
function add_device() { // This will add a device using the data passed encoded with json // FIXME: Execution flow through this function could be improved global $config; $app = \Slim\Slim::getInstance(); $data = json_decode(file_get_contents('php://input'), true); // Default status & code to error and change it if we need to. $status = 'error'; $code = 500; // keep scrutinizer from complaining about snmpver not being set for all execution paths $snmpver = 'v2c'; if (empty($data)) { $message = 'No information has been provided to add this new device'; } elseif (empty($data['hostname'])) { $message = 'Missing the device hostname'; } $hostname = $data['hostname']; $port = $data['port'] ? mres($data['port']) : $config['snmp']['port']; $transport = $data['transport'] ? mres($data['transport']) : 'udp'; $poller_group = $data['poller_group'] ? mres($data['poller_group']) : 0; $force_add = $data['force_add'] ? mres($data['force_add']) : 0; if ($data['version'] == 'v1' || $data['version'] == 'v2c') { if ($data['community']) { $config['snmp']['community'] = array($data['community']); } $snmpver = mres($data['version']); } elseif ($data['version'] == 'v3') { $v3 = array('authlevel' => mres($data['authlevel']), 'authname' => mres($data['authname']), 'authpass' => mres($data['authpass']), 'authalgo' => mres($data['authalgo']), 'cryptopass' => mres($data['cryptopass']), 'cryptoalgo' => mres($data['cryptoalgo'])); array_push($config['snmp']['v3'], $v3); $snmpver = 'v3'; } else { $code = 400; $status = 'error'; $message = "You haven't specified an SNMP version to use"; } if (empty($message)) { $result = addHost($hostname, $snmpver, $port, $transport, 1, $poller_group, $force_add); if ($result) { $code = 201; $status = 'ok'; $message = "Device {$hostname} has been added successfully"; } else { $message = "Failed adding {$hostname}"; } } $app->response->setStatus($code); $output = array('status' => $status, 'message' => $message); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
function addHost($host, $snmpver, $port = '161', $transport = 'udp', $quiet = '0') { global $config; list($hostshort) = explode(".", $host); // Test Database Exists if (dbFetchCell("SELECT COUNT(*) FROM `devices` WHERE `hostname` = ?", array($host)) == '0') { // Test if IP or Hostname if (!inet_pton($host)) { // Test reachability if (isPingable($host)) { $added = 0; if (empty($snmpver)) { // Try SNMPv2c $snmpver = 'v2c'; $ret = addHost($host, $snmpver); if (!$ret) { //Try SNMPv3 $snmpver = 'v3'; $ret = addHost($host, $snmpver); if (!$ret) { // Try SNMPv1 $snmpver = 'v1'; return addHost($host, $snmpver); } else { return $ret; } } else { return $ret; } } if ($snmpver === "v3") { // Try each set of parameters from config foreach ($config['snmp']['v3'] as $v3) { $device = deviceArray($host, NULL, $snmpver, $port, $transport, $v3); if ($quiet == '0') { print_message("Trying v3 parameters " . $v3['authname'] . "/" . $v3['authlevel'] . " ... "); } if (isSNMPable($device)) { $snmphost = snmp_get($device, "sysName.0", "-Oqv", "SNMPv2-MIB"); if (empty($snmphost) or $snmphost == $host || ($hostshort = $host)) { $device_id = createHost($host, NULL, $snmpver, $port, $transport, $v3); return $device_id; } else { if ($quiet == '0') { print_error("Given hostname does not match SNMP-read hostname ({$snmphost})!"); } } } else { if ($quiet == '0') { print_error("No reply on credentials " . $v3['authname'] . "/" . $v3['authlevel'] . " using {$snmpver}"); } } } } elseif ($snmpver === "v2c" or $snmpver === "v1") { // try each community from config foreach ($config['snmp']['community'] as $community) { $device = deviceArray($host, $community, $snmpver, $port, $transport, NULL); if ($quiet == '0') { print_message("Trying community {$community} ..."); } if (isSNMPable($device)) { $snmphost = snmp_get($device, "sysName.0", "-Oqv", "SNMPv2-MIB"); if ($snmphost == "" || $snmphost && ($snmphost == $host || ($hostshort = $host))) { $device_id = createHost($host, $community, $snmpver, $port, $transport); return $device_id; } else { if ($quiet == '0') { print_error("Given hostname does not match SNMP-read hostname ({$snmphost})!"); } } } else { if ($quiet == '0') { print_error("No reply on community {$community} using {$snmpver}"); } } } } else { if ($quiet == '0') { print_error("Unsupported SNMP Version \"{$snmpver}\"."); } } if (!$device_id) { // Failed SNMP if ($quiet == '0') { print_error("Could not reach {$host} with given SNMP community using {$snmpver}"); } } } else { // failed Reachability if ($quiet == '0') { print_error("Could not ping {$host}"); } } } else { // Failed DNS lookup if ($quiet == '0') { print_error("{$host} looks like an IP address, please use FQDN"); } } } else { // found in database if ($quiet == '0') { print_error("Already got host {$host}"); } } return 0; }