std::string NSClientSocket::parseRequest(std::string buffer) { strEx::token pwd = strEx::getToken(buffer, '&'); NSC_DEBUG_MSG("Password: "******"NSClient", "password", "")) ) return "ERROR: Invalid password."; if (pwd.second.empty()) return "ERRRO: No command specified."; strEx::token cmd = strEx::getToken(pwd.second, '&'); if (cmd.first.empty()) return "ERRRO: No command specified."; NSC_DEBUG_MSG("Command: " + cmd.first); std::string message, perf; NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first.c_str(), cmd.second.c_str(), '&', message, perf); int c = atoi(cmd.first.c_str()); switch (c) { case REQ_UPTIME: // Some check_nt commands has no return code syntax case REQ_MEMUSE: case REQ_CPULOAD: case REQ_CLIENTVERSION: case REQ_USEDDISKSPACE: return message; case REQ_SERVICESTATE: // Some check_nt commands return the return code (coded as a string) case REQ_PROCSTATE: return NSCHelper::translateReturn(ret) + "&" + message; default: // "New" check_nscp also returns performance data if (perf.empty()) return NSCHelper::translateReturn(ret) + "&" + message; return NSCHelper::translateReturn(ret) + "&" + message + "|" + perf; } }
void CheckExternalScripts::addAllScriptsFrom(std::string str_path) { std::string pattern = "*.*"; boost::filesystem::path path(str_path); if (!boost::filesystem::is_directory(path)) { if (path.has_relative_path()) path = get_base_path() / path; if (!boost::filesystem::is_directory(path)) { file_helpers::patterns::pattern_type split_path = file_helpers::patterns::split_pattern(path); if (!boost::filesystem::is_directory(split_path.first)) { NSC_LOG_ERROR_STD("Path was not found: " + split_path.first.string()); return; } path = split_path.first; pattern = split_path.second.string(); } } NSC_DEBUG_MSG("Using script path: " + path.string()); boost::regex re; try { std::string pre = file_helpers::patterns::glob_to_regexp(pattern); NSC_DEBUG_MSG("Using regexp: " + pre); re = pre; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Invalid pattern: " + pattern, e); return; } boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr(path); itr != end_itr; ++itr) { if (!is_directory(itr->status())) { std::string name = file_helpers::meta::get_filename(itr->path()); if (regex_match(name, re)) add_command(name, itr->path().string()); } } }
void log_args(const Plugin::QueryRequestMessage::Request &request) { std::stringstream ss; for (int i = 0; i < request.arguments_size(); i++) { if (i > 0) ss << " "; ss << request.arguments(i); } NSC_DEBUG_MSG("Created command: " + ss.str()); }
bool Scheduler::handle_schedule(schedules::target_object item) { try { std::string response; nscapi::core_helper ch(get_core(), get_id()); if (!ch.simple_query(item->command.c_str(), item->arguments, response)) { NSC_LOG_ERROR("Failed to execute: " + item->command); if (item->channel.empty()) { NSC_LOG_ERROR_WA("No channel specified for ", item->get_alias()); return true; } nscapi::protobuf::functions::create_simple_submit_request(item->channel, item->command, NSCAPI::query_return_codes::returnUNKNOWN, "Command was not found: " + item->command, "", response); std::string result; get_core()->submit_message(item->channel, response, result); return true; } Plugin::QueryResponseMessage resp_msg; resp_msg.ParseFromString(response); Plugin::QueryResponseMessage resp_msg_send; resp_msg_send.mutable_header()->CopyFrom(resp_msg.header()); BOOST_FOREACH(const Plugin::QueryResponseMessage::Response &p, resp_msg.payload()) { if (nscapi::report::matches(item->report, nscapi::protobuf::functions::gbp_to_nagios_status(p.result()))) resp_msg_send.add_payload()->CopyFrom(p); } if (resp_msg_send.payload_size() > 0) { if (item->channel.empty()) { NSC_LOG_ERROR_STD("No channel specified for " + item->get_alias() + " mssage will not be sent."); return true; } nscapi::protobuf::functions::make_submit_from_query(response, item->channel, item->get_alias(), item->target_id, item->source_id); std::string result; if (!get_core()->submit_message(item->channel, response, result)) { NSC_LOG_ERROR_STD("Failed to submit: " + item->get_alias()); return true; } std::string error; if (!nscapi::protobuf::functions::parse_simple_submit_response(result, error)) { NSC_LOG_ERROR_STD("Failed to submit " + item->get_alias() + ": " + error); return true; } } else { NSC_DEBUG_MSG("Filter not matched for: " + item->get_alias() + " so nothing is reported"); } return true; } catch (nscapi::nscapi_exception &e) { NSC_LOG_ERROR_EXR("Failed to register command: ", e); return false; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Exception: ", e); return false; } catch (...) { NSC_LOG_ERROR_EX(item->get_alias()); return false; } }
void smtp_client::connection::connected(boost::asio::ip::tcp::resolver::iterator iter, boost::system::error_code ec) { if (ec) { NSC_LOG_ERROR("smtp failed to connect to " + iter->endpoint().address().to_string() + ": " + ec.message()); iter++; resolved(boost::system::error_code(), iter); return; } NSC_DEBUG_MSG("smtp connected to " + iter->endpoint().address().to_string()); state = BANNER; async_read_response(); }
void handler_impl::handle(nsca::packet p) { std::wstring response; std::string::size_type pos = p.result.find('|'); if (pos != std::string::npos) { std::wstring msg = utf8::cvt<std::wstring>(p.result.substr(0, pos)); std::wstring perf = utf8::cvt<std::wstring>(p.result.substr(++pos)); nscapi::core_helper::submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), nscapi::plugin_helper::int2nagios(p.code), msg, perf, response); } else { std::wstring empty, msg = utf8::cvt<std::wstring>(p.result); nscapi::core_helper::submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), nscapi::plugin_helper::int2nagios(p.code), msg, empty, response); } NSC_DEBUG_MSG(_T("Got response: ") + response); }
void do_matchFirstNumeric(const boost::program_options::variables_map &vm, const std::string key, std::string &target, const std::string var, const std::string bound, const std::string op) { if (vm.count(key)) { std::vector<std::string> bounds = vm[key].as<std::vector<std::string> >(); if (bounds.size() > 1 || !target.empty()) NSC_DEBUG_MSG("Multiple boundries of the same kind is not supported"); if (bounds.size() > 0) { std::string value = bounds.front(); if (value.size() > 3 && value[2] == ':') target = var + "=" + bound + " " + value.substr(0,2) + " " + value.substr(3); else target = var + "=" + bound + op + bounds.front(); } } }
void NSClientSocket::onAccept(simpleSocket::Socket client) { if (!inAllowedHosts(client.getAddrString())) { NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString()); client.close(); return; } simpleSocket::DataBuffer db; client.readAll(db); if (db.getLength() > 0) { std::string incoming(db.getBuffer(), db.getLength()); NSC_DEBUG_MSG_STD("Incoming data: " + incoming); std::string response = parseRequest(incoming); NSC_DEBUG_MSG("Outgoing data: " + response); client.send(response.c_str(), static_cast<int>(response.length()), 0); } client.close(); }
void send(const connection_data target, const collectd::collectd_builder::packet_list &packets) { NSC_DEBUG_MSG("Sending " + str::xtos(packets.size()) + " packets to: " + target.to_string()); BOOST_FOREACH(const collectd::packet &p, packets) { try { boost::asio::io_service io_service; boost::asio::ip::address target_address = boost::asio::ip::address::from_string(target.get_address()); boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::host_name(), ""); boost::asio::ip::udp::resolver::iterator endpoint_iterator = resolver.resolve(query); boost::asio::ip::udp::resolver::iterator end; bool is_multicast = false; if (target_address.is_v4()) { is_multicast = target_address.to_v4().is_multicast(); } #if BOOST_VERSION >= 105300 else if (target_address.is_v6()) { is_multicast = target_address.to_v6().is_multicast(); } #endif if (is_multicast) { while (endpoint_iterator != end) { std::string ss = endpoint_iterator->endpoint().address().to_string(); if (target_address.is_v4() && endpoint_iterator->endpoint().address().is_v4()) { std::cout << endpoint_iterator->endpoint().address().to_string() << std::endl; udp_sender s(io_service, endpoint_iterator->endpoint(), target_address, target.get_int_port()); s.send_data(p.get_buffer()); io_service.run(); } endpoint_iterator++; } } else { udp_sender s(io_service, target_address, target.get_int_port()); s.send_data(p.get_buffer()); io_service.run(); } } catch (std::exception& e) { NSC_LOG_ERROR_STD(utf8::utf8_from_native(e.what())); } } }
void smtp_client::connection::resolved(boost::system::error_code ec,boost::asio::ip::tcp::resolver::iterator iter) { if (ec) { NSC_LOG_ERROR("smtp failed resolving: " + ec.message()); boost::lock_guard<boost::mutex> lg(sc->m); sc->active_connection.reset(); return; } if (iter == boost::asio::ip::tcp::resolver::iterator()) { NSC_LOG_ERROR("smtp ran out of server addresses"); boost::lock_guard<boost::mutex> lg(sc->m); sc->active_connection.reset(); return; } NSC_DEBUG_MSG("smtp connecting to " + iter->endpoint().address().to_string()); serv.async_connect(*iter, boost::bind(&connection::connected, shared_from_this(), iter, _1)); }
std::list<nscp::packet> DistributedClient::send_nossl(std::string host, int timeout, const std::list<nscp::packet> &chunks) { zmq::context_t context(1); zeromq::zeromq_client_handshake_reader handshaker("0987654321", nscp::factory::create_message_envelope_request(0)); zeromq::zeromq_client client(zeromq::zeromq_client::connection_info(host, timeout), &handshaker, &context); client.connect(); std::list<nscp::packet> responses; NSC_DEBUG_MSG_STD(_T("Sending data: ") + to_wstring(chunks.size())); BOOST_FOREACH(const nscp::packet packet, chunks) { zeromq::zeromq_client_message_reader reader(&handshaker, packet); if (client.send(&reader)) { NSC_DEBUG_MSG(_T("Got response: ") + to_wstring(reader.response.signature.payload_type)); responses.push_back(reader.response); } else { NSC_LOG_ERROR(_T("Failed to read response!")); responses.push_back(nscp::factory::create_error(_T("Failed to send data to server."))); } }
bool Scheduler::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { if (mode == NSCAPI::reloadStart) { scheduler_.unset_handler(); scheduler_.clear(); } sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "scheduler"); schedules_.set_path(settings.alias().get_settings_path("schedules")); settings.alias().add_path_to_settings() ("SCHEDULER SECTION", "Section for the Scheduler module.") ; settings.alias().add_key_to_settings() ("threads", sh::int_fun_key<unsigned int>(boost::bind(&schedules::scheduler::set_threads, &scheduler_, _1), 5), "THREAD COUNT", "Number of threads to use.") ; settings.alias().add_path_to_settings() ("schedules", sh::fun_values_path(boost::bind(&Scheduler::add_schedule, this, _1, _2)), "SCHEDULER SECTION", "Section for the Scheduler module.", "SCHEDULE", "For more configuration options add a dedicated section") ; settings.alias().add_templates() ("schedules", "plus", "Add a simple schedule", "Add a simple scheduled job for passive monitoring", "{" "\"fields\": [ " " { \"id\": \"alias\", \"title\" : \"Alias\", \"type\" : \"input\", \"desc\" : \"This will identify the command\"} , " " { \"id\": \"command\", \"title\" : \"Command\", \"type\" : \"data-choice\", \"desc\" : \"The name of the command to execute\",\"exec\" : \"CheckExternalScripts list --json --query\" } , " " { \"id\": \"args\", \"title\" : \"Arguments\", \"type\" : \"input\", \"desc\" : \"Command line arguments for the command\" } , " " { \"id\": \"cmd\", \"key\" : \"command\", \"title\" : \"A\", \"type\" : \"hidden\", \"desc\" : \"A\" } " " ], " "\"events\": { " "\"onSave\": \"(function (node) { node.save_path = self.path; var f = node.get_field('cmd'); f.key = node.get_field('alias').value(); var val = node.get_field('command').value(); if (node.get_field('args').value()) { val += ' ' + node.get_field('args').value(); }; f.value(val)})\"" "}" "}") ; settings.register_all(); settings.notify(); schedules_.ensure_default(); BOOST_FOREACH(const schedules::schedule_handler::object_list_type::value_type &o, schedules_.get_object_list()) { if (o->duration && (*o->duration).total_seconds() == 0) { NSC_LOG_ERROR("WE cant add schedules with 0 duration: " + o->to_string()); continue; } if (o->duration && o->schedule) { NSC_LOG_ERROR("WE cant add schedules with both duration and schedule: " + o->to_string()); continue; } if (!o->duration && !o->schedule) { NSC_LOG_ERROR("WE need wither duration or schedule: " + o->to_string()); continue; } NSC_DEBUG_MSG("Adding scheduled item: " + o->to_string()); scheduler_.add_task(o); } if (mode == NSCAPI::normalStart) { scheduler_.set_handler(this); scheduler_.start(); } if (mode == NSCAPI::reloadStart) { scheduler_.set_handler(this); scheduler_.start(); } return true; }
void smtp_client::connection::send_raw(std::string raw) { NSC_DEBUG_MSG("smtp sending " + raw); boost::shared_ptr<boost::asio::const_buffers_1> rb(new boost::asio::const_buffers_1 (boost::asio::buffer(raw))); boost::asio::async_write(serv, *rb, boost::bind(&connection::sent, shared_from_this(), rb, _1, _2)); }
void smtp_client::connection::got_response(std::string resp, boost::system::error_code ec, size_t bytes) { if (ec) { NSC_LOG_ERROR("smtp failure in reading: " + ec.message()); boost::lock_guard<boost::mutex> lg(sc->m); if (cur) sc->ready.push_back(cur); sc->active_connection.reset(); return; } std::string line; line.reserve(bytes); for (size_t i = 0; i < bytes; i++) line += char(readbuf.sbumpc()); resp += line; if (line.length() >= 4 && line[3] == '-') { boost::asio::async_read_until(serv, readbuf, "\r\n", boost::bind(&connection::got_response, shared_from_this(), resp, _1, _2)); return; } NSC_DEBUG_MSG("smtp read " + resp); bool broken_resp = resp.empty() || !('2' <= resp[0] && resp[0] <= '5') || (resp[0] == '3' && (state != DATA || resp.substr(0,3) != "354")); // FIXME deferral / drop-on-the-floor notifications if (broken_resp || resp[0] == '4') { boost::lock_guard<boost::mutex> lg(sc->m); if (cur) sc->deferred.push_back(cur); } if (broken_resp || state == QUIT) { NSC_LOG_ERROR("smtp terminating"); boost::lock_guard<boost::mutex> lg(sc->m); sc->active_connection.reset(); return; } if ((resp[0] == '4' || resp[0] == '5' || state == DATA_354) && (resp.substr(0,3) != "502" || state != EHLO)) { cur.reset(); if (sc->ready.empty() || state <= RSET) { state = QUIT; send_line("QUIT"); } else { state = RSET; send_line("RSET"); } return; } assert(!resp.empty()); switch (state) { case BANNER: assert(resp[0] == '2'); state = EHLO; send_line("EHLO " + config["canonical-name"]); break; case EHLO: if (resp.substr(0,3) == "502") { state = HELO; send_line("HELO" + config["canonical-name"]); break; } assert(resp[0] == '2'); /* passthrough */ case HELO: case RSET: assert(resp[0] == '2'); assert(!cur); { boost::lock_guard<boost::mutex> lg(sc->m); if (sc->ready.empty()) { state = QUIT; send_line("QUIT"); break; } cur = sc->ready.front(); sc->ready.pop_front(); } assert(cur); state = MAIL_FROM; send_line("MAIL FROM: <" + cur->sender + ">"); break; case MAIL_FROM: assert(resp[0] == '2'); assert(cur); state = RCPT_TO; send_line("RCPT TO: <" + cur->recipient + ">"); break; case RCPT_TO: assert(resp[0] == '2'); assert(cur); state = DATA; send_line("DATA"); break; case DATA: assert(resp.substr(0,3) == "354"); assert(cur); state = DATA_354; send_raw(cur->data + ".\r\n"); break; case DATA_354: case QUIT: assert(0); // handled above break; } }
bool CheckExternalScripts::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) { try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "external scripts"); aliases_.set_path(settings.alias().get_settings_path("alias")); std::string wrappings_path = settings.alias().get_settings_path("wrappings"); boost::filesystem::path scriptRoot; std::string scriptDirectory; std::map<std::string, std::string> wrappings; settings.alias().add_path_to_settings() ("wrappings", sh::string_map_path(&wrappings) , "Script wrappings", "A list of templates for defining script commands.\nEnter any command line here and they will be expanded by scripts placed under the wrapped scripts section. %SCRIPT% will be replaced by the actual script an %ARGS% will be replaced by any given arguments.", "WRAPPING", "An external script wrapping") ("alias", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)), "Command aliases", "A list of aliases for already defined commands (with arguments).\n" "An alias is an internal command that has been predefined to provide a single command without arguments. Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)", "ALIAS", "Query alias") ; settings.register_all(); settings.notify(); settings.clear(); if (wrappings.find("ps1") == wrappings.end()) { wrappings["ps1"] = "cmd /c echo If (-Not (Test-Path \"scripts\\%SCRIPT%\") ) { Write-Host \"UNKNOWN: Script `\"%SCRIPT%`\" not found.\"; exit(3) }; scripts\\%SCRIPT% $ARGS$; exit($lastexitcode) | powershell.exe /noprofile -command -"; settings.register_key(wrappings_path, "ps1", NSCAPI::key_string, "POWERSHELL WRAPPING", "Command line used for executing wrapped ps1 (powershell) scripts", "cmd /c echo If (-Not (Test-Path \"scripts\\%SCRIPT%\") ) { Write-Host \"UNKNOWN: Script `\"%SCRIPT%`\" not found.\"; exit(3) }; scripts\\%SCRIPT% $ARGS$; exit($lastexitcode) | powershell.exe /noprofile -command -", false); settings.set_static_key(wrappings_path, "ps1", wrappings["ps1"]); } if (wrappings.find("vbs") == wrappings.end()) { wrappings["vbs"] = "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%"; settings.register_key(wrappings_path, "vbs", NSCAPI::key_string, "Visual basic script", "Command line used for wrapped vbs scripts", "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%", false); settings.set_static_key(wrappings_path, "vbs", wrappings["vbs"]); } if (wrappings.find("bat") == wrappings.end()) { wrappings["bat"] = "scripts\\\\%SCRIPT% %ARGS%"; settings.register_key(wrappings_path, "bat", NSCAPI::key_string, "Batch file", "Command used for executing wrapped batch files", "scripts\\\\%SCRIPT% %ARGS%", false); settings.set_static_key(wrappings_path, "bat", wrappings["bat"]); } if (aliases_.empty()) { NSC_DEBUG_MSG("No aliases found (adding default)"); add_alias("alias_cpu", "check_cpu"); add_alias("alias_cpu_ex", "check_cpu \"warn=load > $ARG1$\" \"crit=load > $ARG2$\" time=5m time=1m time=30s"); add_alias("alias_mem", "check_memory"); add_alias("alias_up", "check_uptime"); add_alias("alias_disk", "check_drivesize"); add_alias("alias_disk_loose", "check_drivesize"); add_alias("alias_volumes", "check_drivesize"); add_alias("alias_volumes_loose", "check_drivesize"); add_alias("alias_service", "check_service"); add_alias("alias_service_ex", "check_service \"exclude=Net Driver HPZ12\" \"exclude=Pml Driver HPZ12\" exclude=stisvc"); add_alias("alias_process", "check_process \"process=$ARG1$\" \"crit=state != 'started'\""); add_alias("alias_process_stopped", "check_process \"process=$ARG1$\" \"crit=state != 'stopped'\""); add_alias("alias_process_count", "check_process \"process=$ARG1$\" \"warn=count > $ARG2$\" \"crit=count > $ARG3$\""); add_alias("alias_process_hung", "check_process \"filter=is_hung\" \"crit=count>0\""); add_alias("alias_event_log", "check_eventlog"); add_alias("alias_file_size", "check_files \"path=$ARG1$\" \"crit=size > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${size}\" max-dir-depth=10"); add_alias("alias_file_age", "check_files \"path=$ARG1$\" \"crit=written > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${written}\" max-dir-depth=10"); add_alias("alias_sched_all", "check_tasksched show-all \"syntax=${title}: ${exit_code}\" \"crit=exit_code ne 0\""); add_alias("alias_sched_long", "check_tasksched \"filter=status = 'running'\" \"detail-syntax=${title} (${most_recent_run_time})\" \"crit=most_recent_run_time < -$ARG1$\""); add_alias("alias_sched_task", "check_tasksched show-all \"filter=title eq '$ARG1$'\" \"detail-syntax=${title} (${exit_code})\" \"crit=exit_code ne 0\""); // add_alias("alias_updates", "check_updates -warning 0 -critical 0"); } settings.alias().add_key_to_settings() ("timeout", sh::uint_key(&timeout, 60), "Command timeout", "The maximum time in seconds that a command can execute. (if more then this execution will be aborted). NOTICE this only affects external commands not internal ones.") ("allow arguments", sh::bool_key(&allowArgs_, false), "Allow arguments when executing external scripts", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.") ("allow nasty characters", sh::bool_key(&allowNasty_, false), "Allow certain potentially dangerous characters in arguments", "This option determines whether or not the we will allow clients to specify nasty (as in |`&><'\"\\[]{}) characters in arguments.") ("script path", sh::string_key(&scriptDirectory), "Load all scripts in a given folder", "Load all scripts in a given directory and use them as commands.") ("script root", sh::path_key(&scriptRoot, "${scripts}"), "Script root folder", "Root path where all scripts are contained (You can not upload/download scripts outside this folder).") ; settings.register_all(); settings.notify(); settings.clear(); provider_.reset(new script_provider(get_id(), get_core(), settings.alias().get_settings_path("scripts"), scriptRoot, wrappings)); settings.alias().add_path_to_settings() ("External script settings", "General settings for the external scripts module (CheckExternalScripts).") ("scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_command, this, _1, _2)), "External scripts", "A list of scripts available to run from the CheckExternalScripts module. Syntax is: `command=script arguments`", "SCRIPT", "For more configuration options add a dedicated section (if you add a new section you can customize the user and various other advanced features)") ("wrapped scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)), "Wrapped scripts", "A list of wrapped scripts (ie. script using a template mechanism).\nThe template used will be defined by the extension of the script. Thus a foo.ps1 will use the ps1 wrapping from the wrappings section.", "WRAPPED SCRIPT", "A wrapped script definitions") ; settings.alias().add_templates() ("scripts", "plus", "Add a simple script", "Add binding for a simple script", "{" "\"fields\": [ " " { \"id\": \"alias\", \"title\" : \"Alias\", \"type\" : \"input\", \"desc\" : \"This will identify the command\"} , " " { \"id\": \"script\", \"title\" : \"Script\", \"type\" : \"data-choice\", \"desc\" : \"The name of the script\",\"exec\" : \"CheckExternalScripts list --json\" } , " " { \"id\": \"args\", \"title\" : \"Arguments\", \"type\" : \"input\", \"desc\" : \"Command line arguments for the script use $ARG1$ to specify arguments\" } , " " { \"id\": \"cmd\", \"key\" : \"command\", \"title\" : \"A\", \"type\" : \"hidden\", \"desc\" : \"A\" } " " ], " "\"events\": { " "\"onSave\": \"(function (node) { node.save_path = self.path; var f = node.get_field('cmd'); f.key = node.get_field('alias').value(); var val = node.get_field('script').value(); if (node.get_field('args').value()) { val += ' ' + node.get_field('args').value(); }; f.value(val)})\"" "}" "}") ("alias", "plus", "Add an alias", "Add binding for an alias", "{" "\"fields\": [ " " { \"id\": \"alias\", \"title\" : \"Alias\", \"type\" : \"input\", \"desc\" : \"This will identify the command\"} , " " { \"id\": \"command\", \"title\" : \"Command\", \"type\" : \"data-choice\", \"desc\" : \"The name of the command to execute\",\"exec\" : \"CheckExternalScripts list --json --query\" } , " " { \"id\": \"args\", \"title\" : \"Arguments\", \"type\" : \"input\", \"desc\" : \"Command line arguments for the command. use $ARG1$ to specify arguments\" } , " " { \"id\": \"cmd\", \"key\" : \"command\", \"title\" : \"A\", \"type\" : \"hidden\", \"desc\" : \"A\" } " " ], " "\"events\": { " "\"onSave\": \"(function (node) { node.save_path = self.path; \nvar f = node.get_field('cmd'); \nf.key = node.get_field('alias').value(); \nvar val = node.get_field('command').value(); \nif (node.get_field('args').value()) { \nval += ' ' + node.get_field('args').value(); }; \nf.value(val)})\"" "}" "}") ; settings.register_all(); settings.notify(); if (!scriptDirectory.empty()) { addAllScriptsFrom(scriptDirectory); } aliases_.add_samples(get_settings_proxy()); aliases_.add_missing(get_settings_proxy(), "default", ""); root_ = get_base_path(); nscapi::core_helper core(get_core(), get_id()); BOOST_FOREACH(const boost::shared_ptr<alias::command_object> &o, aliases_.get_object_list()) { core.register_alias(o->get_alias(), "Alias for: " + o->command); } } catch (...) { NSC_LOG_ERROR_EX("loading"); return false; } return true; }
bool CheckExternalScripts::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) { try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "external scripts"); commands_path = settings.alias().get_settings_path("scripts"); aliases_path = settings.alias().get_settings_path("alias"); std::string wrappings_path = settings.alias().get_settings_path("wrappings"); settings.alias().add_path_to_settings() ("wrappings", sh::string_map_path(&wrappings_) , "EXTERNAL SCRIPT WRAPPINGS SECTION", "A list of templates for wrapped scripts.\n%SCRIPT% will be replaced by the actual script an %ARGS% will be replaced by any given arguments.", "WRAPPING", "An external script wrapping") ("alias", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)), "ALIAS SECTION", "A list of aliases available.\n" "An alias is an internal command that has been predefined to provide a single command without arguments. Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)", "ALIAS", "Query alias") ; settings.register_all(); settings.notify(); settings.clear(); if (wrappings_.find("ps1") == wrappings_.end()) { wrappings_["ps1"] = "cmd /c echo scripts\\\\%SCRIPT% %ARGS%; exit($lastexitcode) | powershell.exe -command -"; settings.register_key(wrappings_path, "ps1", NSCAPI::key_string, "POWERSHELL WRAPPING", "", "", false); settings.set_static_key(wrappings_path, "ps1", wrappings_["ps1"]); } if (wrappings_.find("vbs") == wrappings_.end()) { wrappings_["vbs"] = "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%"; settings.register_key(wrappings_path, "vbs", NSCAPI::key_string, "VISUAL BASIC WRAPPING", "", "", false); settings.set_static_key(wrappings_path, "vbs", wrappings_["vbs"]); } if (wrappings_.find("bat") == wrappings_.end()) { wrappings_["bat"] = "scripts\\\\%SCRIPT% %ARGS%"; settings.register_key(wrappings_path, "bat", NSCAPI::key_string, "BATCH FILE WRAPPING", "", "", false); settings.set_static_key(wrappings_path, "bat", wrappings_["bat"]); } if (aliases_.empty()) { NSC_DEBUG_MSG("No aliases found (adding default)"); add_alias("alias_cpu", "check_cpu"); add_alias("alias_cpu_ex", "check_cpu \"warn=load > $ARG1$\" \"crit=load > $ARG2$\" time=5m time=1m time=30s"); add_alias("alias_mem", "check_memory"); add_alias("alias_up", "check_uptime"); add_alias("alias_disk", "check_drivesize"); add_alias("alias_disk_loose", "check_drivesize"); add_alias("alias_volumes", "check_drivesize"); add_alias("alias_volumes_loose", "check_drivesize"); add_alias("alias_service", "check_service"); add_alias("alias_service_ex", "check_service \"exclude=Net Driver HPZ12\" \"exclude=Pml Driver HPZ12\" exclude=stisvc"); add_alias("alias_process", "check_process \"process=$ARG1$\" \"crit=state != 'started'\""); add_alias("alias_process_stopped", "check_process \"process=$ARG1$\" \"crit=state != 'stopped'\""); add_alias("alias_process_count", "check_process \"process=$ARG1$\" \"warn=count > $ARG2$\" \"crit=count > $ARG3$\""); add_alias("alias_process_hung", "check_process \"filter=is_hung\" \"crit=count>0\""); add_alias("alias_event_log", "check_eventlog"); add_alias("alias_file_size", "check_files \"path=$ARG1$\" \"crit=size > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${size}\" max-dir-depth=10"); add_alias("alias_file_age", "check_files \"path=$ARG1$\" \"crit=written > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${written}\" max-dir-depth=10"); add_alias("alias_sched_all", "check_tasksched show-all \"syntax=${title}: ${exit_code}\" \"crit=exit_code ne 0\""); add_alias("alias_sched_long", "check_tasksched \"filter=status = 'running'\" \"detail-syntax=${title} (${most_recent_run_time})\" \"crit=most_recent_run_time < -$ARG1$\""); add_alias("alias_sched_task", "check_tasksched show-all \"filter=title eq '$ARG1$'\" \"detail-syntax=${title} (${exit_code})\" \"crit=exit_code ne 0\""); // add_alias("alias_updates", "check_updates -warning 0 -critical 0"); } settings.alias().add_path_to_settings() ("EXTERNAL SCRIPT SECTION", "Section for external scripts configuration options (CheckExternalScripts).") ("scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_command, this, _1, _2)), "SCRIPT SECTION", "A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>", "SCRIPT", "For more configuration options add a dedicated section (if you add a new section you can customize the user and various other advanced features)") ("wrapped scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)), "WRAPPED SCRIPTS SECTION", "A list of wrapped scripts (ie. scruts using a template mechanism). The template used will be defined by the extension of the script.", "WRAPPED SCRIPT", "A wrapped script defenitions") ; settings.alias().add_key_to_settings() ("timeout", sh::uint_key(&timeout, 60), "COMMAND TIMEOUT", "The maximum time in seconds that a command can execute. (if more then this execution will be aborted). NOTICE this only affects external commands not internal ones.") ("allow arguments", sh::bool_key(&allowArgs_, false), "COMMAND ARGUMENT PROCESSING", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.") ("allow nasty characters", sh::bool_key(&allowNasty_, false), "COMMAND ALLOW NASTY META CHARS", "This option determines whether or not the we will allow clients to specify nasty (as in |`&><'\"\\[]{}) characters in arguments.") ("script path", sh::string_key(&scriptDirectory_), "SCRIPT DIRECTORY", "Load all scripts in a directory and use them as commands. Probably dangerous but useful if you have loads of scripts :)") ; settings.register_all(); settings.notify(); if (!scriptDirectory_.empty()) { addAllScriptsFrom(scriptDirectory_); } root_ = get_base_path(); nscapi::core_helper core(get_core(), get_id()); BOOST_FOREACH(const commands::command_handler::object_list_type::value_type &o, commands_.object_list) { core.register_alias(o.second.tpl.alias, "External script: " + o.second.command); } BOOST_FOREACH(const alias::command_handler::object_list_type::value_type &o, aliases_.object_list) { core.register_alias(o.second.tpl.alias, "Alias for: " + o.second.command); } } catch (...) { NSC_LOG_ERROR_EX("loading"); return false; } return true; }