Exemplo n.º 1
0
int main(int argc, char * const argv[])
{
	int err;
	int verify = 0;
	struct sdp_work *cmd_head = NULL;
	char const *conf;
	char const *base_path = get_base_path(argv[0]);
	char const *conf_path = get_global_conf_path();

	err = parse_opts(argc, argv, &conf_path, &verify, &cmd_head);
	if (err < 0)
		return EXIT_FAILURE;
	else if (err > 0)
		return EXIT_SUCCESS;

	// Get list of machines...
	conf = conf_file_name("imx_usb.conf", base_path, conf_path);
	if (conf == NULL)
		return EXIT_FAILURE;

	struct mach_id *list = parse_imx_conf(conf);
	if (!list)
		return EXIT_FAILURE;

	err = do_autodetect_dev(base_path, conf_path, list, verify, cmd_head);
	if (err < 0)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}
Exemplo n.º 2
0
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());
		}
	}
}
Exemplo n.º 3
0
Arquivo: types.c Projeto: 8l/awl
void awlenv_add_core_lib(awlenv* e) {
    char* awl_base = get_base_path();

    char* corelib = path_join(awl_base, "lib/core");

    awlval* args = awlval_sexpr();
    args = awlval_add(args, awlval_str(corelib));
    awlval_del(builtin_import(e, args));

    free(awl_base);
    free(corelib);
}
Exemplo n.º 4
0
void CheckExternalScripts::addAllScriptsFrom(std::string str_path) {
	boost::filesystem::path path(str_path);
	if (path.has_relative_path())
		path = get_base_path() / 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());

	boost::regex pattern(split_path.second.string());
	boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
	for ( boost::filesystem::directory_iterator itr( split_path.first ); itr != end_itr; ++itr ) {
		if ( !is_directory(itr->status()) ) {
			std::string name = file_helpers::meta::get_filename(itr->path());
			if (regex_match(name, pattern))
				add_command(name, (split_path.first / name).string());
		}
	}
}
Exemplo n.º 5
0
bool LUAScript::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	try {

		root_ = get_base_path();
		nscp_runtime_.reset(new scripts::nscp::nscp_runtime_impl(get_id(), get_core()));
		lua_runtime_.reset(new lua::lua_runtime(utf8::cvt<std::string>(root_.string())));
		scripts_.reset(new scripts::script_manager<lua::lua_traits>(lua_runtime_, nscp_runtime_, get_id(), utf8::cvt<std::string>(alias)));

		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(alias, "lua");

		settings.alias().add_path_to_settings()
			("LUA SCRIPT SECTION", "Section for the LUAScripts module.")

			("scripts", sh::fun_values_path(boost::bind(&LUAScript::loadScript, this, _1, _2)), 
			"LUA SCRIPTS SECTION", "A list of scripts available to run from the LuaSCript module.",
			"SCRIPT DEFENTION", "For more configuration options add a dedicated section")
			;

		settings.register_all();
		settings.notify();

// 		if (!scriptDirectory_.empty()) {
// 			addAllScriptsFrom(scriptDirectory_);
// 		}

		scripts_->load_all();
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("load", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("load");
		return false;
	}

	return true;
}
Exemplo n.º 6
0
bool CheckMKClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	std::map<std::wstring,std::wstring> commands;

	try {
		root_ = get_base_path();
		nscp_runtime_.reset(new scripts::nscp::nscp_runtime_impl(get_id(), get_core()));
		lua_runtime_.reset(new lua::lua_runtime(utf8::cvt<std::string>(root_.string())));
		lua_runtime_->register_plugin(boost::shared_ptr<check_mk::check_mk_plugin>(new check_mk::check_mk_plugin()));
		scripts_.reset(new scripts::script_manager<lua::lua_traits>(lua_runtime_, nscp_runtime_, get_id(), utf8::cvt<std::string>(alias)));


		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias("check_mk", alias, "client");
		target_path = settings.alias().get_settings_path("targets");

		settings.alias().add_path_to_settings()
			("CHECK MK CLIENT SECTION", "Section for NSCP active/passive check module.")

			("handlers", sh::fun_values_path(boost::bind(&CheckMKClient::add_command, this, _1, _2)), 
			"CLIENT HANDLER SECTION", "",
			"CLIENT", "For more configuration options add a dedicated section")

			("targets", sh::fun_values_path(boost::bind(&CheckMKClient::add_target, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "",
			"TARGET", "For more configuration options add a dedicated section")

			("scripts", sh::fun_values_path(boost::bind(&CheckMKClient::add_script, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "",
			"SCRIPT", "For more configuration options add a dedicated section")
			;

		settings.alias().add_key_to_settings()
			("channel", sh::string_key(&channel_, "CheckMK"),
			"CHANNEL", "The channel to listen to.")

			;


		settings.register_all();
		settings.notify();

		targets.add_samples(get_settings_proxy(), target_path);
		targets.add_missing(get_settings_proxy(), target_path, "default", "", true);

		if (scripts_->empty()) {
			add_script("default", "default_check_mk.lua");
		}

		nscapi::core_helper core(get_core(), get_id());
		core.register_channel(channel_);

		scripts_->load_all();

	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_EXR("Load", e);
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("Load", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("Load");
		return false;
	}
	return true;
}
Exemplo n.º 7
0
int main(int argc, char * const argv[])
{
	struct sdp_dev *p_id;
	struct mach_id *mach;
	libusb_device **devs;
	libusb_device *dev;
	int r;
	int err;
	ssize_t cnt;
	libusb_device_handle *h = NULL;
	int config = 0;
	int verify = 0;
	struct sdp_work *curr;
	struct sdp_work *cmd_head = NULL;
	char const *conf;
	char const *base_path = get_base_path(argv[0]);
	char const *conf_path = "/etc/imx-loader.d/";

	err = parse_opts(argc, argv, &conf_path, &verify, &cmd_head);
	if (err < 0)
		return -1;

	// Get list of machines...
	conf = conf_file_name("imx_usb.conf", base_path, conf_path);
	if (conf == NULL)
		return -1;

	struct mach_id *list = parse_imx_conf(conf);
	if (!list)
		return -1;

	r = libusb_init(NULL);
	if (r < 0)
		goto out;

	cnt = libusb_get_device_list(NULL, &devs);
	if (cnt < 0)
		goto out;

//	print_devs(devs);
	dev = find_imx_dev(devs, &mach, list);
	if (dev) {
		err = libusb_open(dev, &h);
		if (err)
			printf("%s:Could not open device vid=0x%x pid=0x%x err=%d\n", __func__, mach->vid, mach->pid, err);
	}
	libusb_free_device_list(devs, 1);

	if (!h)
		goto out;

	// Get machine specific configuration file..
	conf = conf_file_name(mach->file_name, base_path, conf_path);
	if (conf == NULL)
		goto out;

	p_id = parse_conf(conf);
	if (!p_id)
		goto out;

	if (p_id->mode == MODE_HID)
		p_id->transfer = &transfer_hid;
	if (p_id->mode == MODE_BULK)
		p_id->transfer = &transfer_bulk;

	// USB private pointer is libusb device handle...
	p_id->priv = h;

	libusb_get_configuration(h, &config);
	printf("%04x:%04x(%s) bConfigurationValue =%x\n",
			mach->vid, mach->pid, p_id->name, config);

	if (libusb_kernel_driver_active(h, 0))
		 libusb_detach_kernel_driver(h, 0);

	err = libusb_claim_interface(h, 0);
	if (err) {
		printf("Claim failed\n");
		goto out;
	}
	printf("Interface 0 claimed\n");
	err = do_status(p_id);
	if (err) {
		printf("status failed\n");
		goto out;
	}

	// By default, use work from config file...
	curr = p_id->work;

	if (cmd_head != NULL)
		curr = cmd_head;

	if (curr == NULL) {
		printf("no job found\n"); 
		goto out;
	}

	while (curr) {
		if (curr->mem)
			perform_mem_work(p_id, curr->mem);
//		printf("jump_mode %x\n", curr->jump_mode);
		if (curr->filename[0]) {
			err = DoIRomDownload(p_id, curr, verify);
		}
		if (err) {
			err = do_status(p_id);
			break;
		}
		if (!curr->next && (!curr->plug || curr != cmd_head))
			break;
		err = do_status(p_id);
		printf("jump_mode %x plug=%i err=%i\n", curr->jump_mode, curr->plug, err);
		if (err) {
			int retry;
			/* Rediscovers device */
			libusb_release_interface(h, 0);
			libusb_close(h);
			libusb_exit(NULL);
			for (retry = 0; retry < 10; retry++) {
				printf("sleeping\n");
				sleep(3);
				printf("done sleeping\n");
				h = open_vid_pid(mach, p_id);
				if (h)
					break;
			}
			if (!h)
				goto out;
		}
		if (curr == cmd_head && curr->plug) {
			curr->plug = 0;
			continue;
		}
		curr = curr->next;
	}

exit:
	libusb_release_interface(h, 0);
out:
	if (h)
		libusb_close(h);
	libusb_exit(NULL);
	return 0;
}
Exemplo n.º 8
0
	IODevice XMLResourceNode::open_file(const std::string &filename, File::OpenMode mode, unsigned int access, unsigned int share, unsigned int flags) const
	{
		return get_file_system().open_file(PathHelp::combine(get_base_path(), filename), mode, access, share, flags);
	}
Exemplo n.º 9
0
int main(int argc, char * const argv[])
{
	struct sdp_dev *p_id;
	int err = 0;
	int config = 0;
	int verify = 0;
	int usertscts = 1;
	int uart_fd;
	struct sdp_work *curr;
	char const *conf;
	char const *ttyfile;
	char const *conffilepath;
	char const *conffile;
	char const *basepath;
#ifndef WIN32
	struct termios orig;
#else
	DCB orig;
#endif

	curr=NULL;

	err = parse_opts(argc, argv, &ttyfile, &conffilepath, &verify, &usertscts, &curr);

	if (err < 0)
		return err;

	// Get machine specific configuration file..
	if ((conffile = strrchr(conffilepath, PATH_SEPARATOR)) == NULL) {
		// Only a file was given as configuration
		basepath = get_base_path(argv[0]);
		conffile = conffilepath;
	} else {
		// A whole path is given as configuration
		basepath = get_base_path(conffilepath);
		conffile++; // Filename starts after slash
	}

	conf = conf_file_name(conffile, basepath, SYSCONFDIR "/imx-loader.d/");
	if (conf == NULL)
		return -1;

	p_id = parse_conf(conf);
	if (!p_id)
		return -1;

	// Open UART and start associating phase...
	err = uart_connect(&uart_fd, ttyfile, usertscts, &orig);

	if (err < 0)
		goto out;

	p_id->transfer = &transfer_uart;

	// UART private pointer is TTY file descriptor...
	p_id->priv = &uart_fd;

	err = do_status(p_id);
	if (err) {
		printf("status failed\n");
		goto out;
	}

	// By default, use work from config file...
	if (curr == NULL)
		curr = p_id->work;

	while (curr) {
		if (curr->mem)
			perform_mem_work(p_id, curr->mem);
//		printf("jump_mode %x\n", curr->jump_mode);
		if (curr->filename[0]) {
			err = DoIRomDownload(p_id, curr, verify);
		}
		if (err) {
			err = do_status(p_id);
			break;
		}
		if (!curr->next && !curr->plug)
			break;
		err = do_status(p_id);
		printf("jump_mode %x plug=%i err=%i\n", curr->jump_mode, curr->plug, err);

		if (err)
			goto out;

		if (curr->plug) {
			curr->plug = 0;
			continue;
		}
		curr = curr->next;
	}

out:
	uart_close(&uart_fd, &orig);
	return err;
}
Exemplo n.º 10
0
bool CheckMKServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	root_ = get_base_path();
	nscp_runtime_.reset(new scripts::nscp::nscp_runtime_impl(get_id(), get_core()));
	lua_runtime_.reset(new lua::lua_runtime(utf8::cvt<std::string>(root_.string())));
	lua_runtime_->register_plugin(boost::shared_ptr<check_mk::check_mk_plugin>(new check_mk::check_mk_plugin()));
	scripts_.reset(new scripts::script_manager<lua::lua_traits>(lua_runtime_, nscp_runtime_, get_id(), utf8::cvt<std::string>(alias)));
	handler_.reset(new handler_impl(scripts_));

	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias("check_mk", alias, "server");

	settings.alias().add_path_to_settings()
		("CHECK MK SERVER SECTION", "Section for check_mk (CheckMKServer.dll) protocol options.")

		("scripts", sh::fun_values_path(boost::bind(&CheckMKServer::add_script, this, _1, _2)), 
		"REMOTE TARGET DEFINITIONS", "",
		"TARGET", "For more configuration options add a dedicated section")

		;

	settings.alias().add_key_to_settings()
		("port", sh::string_key(&info_.port_, "6556"),
		"PORT NUMBER", "Port to use for check_mk.")

		;

	socket_helpers::settings_helper::add_core_server_opts(settings, info_);
	socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, false);

	settings.register_all();
	settings.notify();

	if (scripts_->empty()) {
		add_script("default", "default_check_mk.lua");
	}

#ifndef USE_SSL
	if (info_.use_ssl) {
		NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)"));
		return false;
	}
#endif
	NSC_LOG_ERROR_LISTS(info_.validate());

	std::list<std::string> errors;
	info_.allowed_hosts.refresh(errors);
	NSC_LOG_ERROR_LISTS(errors);
	NSC_DEBUG_MSG_STD("Allowed hosts definition: " + info_.allowed_hosts.to_string());

	boost::asio::io_service io_service_;

	scripts_->load_all();


	if (mode == NSCAPI::normalStart) {
		server_.reset(new check_mk::server::server(info_, handler_));
		if (!server_) {
			NSC_LOG_ERROR_STD("Failed to create server instance!");
			return false;
		}
		server_->start();
	}
	return true;
}
Exemplo n.º 11
0
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;
}
Exemplo n.º 12
0
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;
}