NRPE Error: returns 0 byte

This support forum board is for support questions relating to Nagios XI, our flagship commercial network monitoring solution.
Locked
sajid4u2c
Posts: 46
Joined: Thu Mar 15, 2018 10:55 am

NRPE Error: returns 0 byte

Post by sajid4u2c »

Hi All,

I am using check_mssql.ps1 plugin to check the failed SQL at the instance level.

The plugin was working quite well alerting on the failed jobs.
But from last six days the state changed to UNKNOWN state returning the below output.
I ran these checks from tow different Nagios servers where NRPE version is different. Still no luck.
Please suggest.

Nrpe Version: 2.12
Service : SQL_Job_Status
Status : Unknown
Status information : CHECK_NRPE: Received 0 bytes from daemon. Check the remote server logs for error messages.

Nrpe Version: 3.2.1
Service : SQL_Job_Status
Status : Unknown
Status information : CHECK_NRPE: Receive header underflow-only 0 bytes received (4 expected )

NSClient.log file :

2019-04-18 10:33:21: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 10:39:35: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 10:48:18: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 10:48:35: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 10:57:35: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 11:03:15: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 11:06:35: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 11:15:34: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid
2019-04-18 11:18:13: error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid

Attached the NSClient++.ini file also. Thanks.

Code: Select all

# If you want to fill this file with all avalible options run the following command:
#   nscp settings --generate --add-defaults --load-all
# If you want to activate a module and bring in all its options use:
#   nscp settings --activate-module <MODULE NAME> --add-defaults
# For details run: nscp settings --help


; Undocumented section
[/settings/default]

; CACHE ALLOWED HOSTS - If host names (DNS entries) should be cached, improves speed and security somewhat but won't allow you to have dynamic IPs for your Nagios server.
cache allowed hosts = 1

; TIMEOUT - Timeout when reading packets on incoming sockets. If the data has not arrived within this time we will bail out.
timeout = 10

; ALLOWED HOSTS - A comaseparated list of allowed hosts. You can use netmasks (/ syntax) or * to create ranges.
allowed hosts = Multiple Nagios server IPs

; INBOX - The default channel to post incoming messages on
inbox = inbox

; PASSWORD - Password used to authenticate against server
password = 

; BIND TO ADDRESS - Allows you to bind server to a specific local address. This has to be a dotted ip address not a host name. Leaving this blank will bind to all available IP addresses.
;bind to = 


; Undocumented section
[/modules]

; SimpleFileWriter - Write status updates to a text file (A bit like the NSCA server does)
SimpleFileWriter = 0

; PythonScript - Loads and processes internal Python scripts
PythonScript = 0

; NSCAClient - NSCA client can be used both from command line and from queries to submit passive checks via NSCA
NSCAClient = 1

; NRDPClient - NRDP client can be used both from command line and from queries to check remote systes via NRDP
NRDPClient = 0

; DotnetPlugin - Plugin to load and manage plugins written in dot net.
DotnetPlugins = 0

; CommandClient - A command line client, generally not used except with "nscp test".
CommandClient = 0

; CheckTaskSched - Check status of your scheduled jobs.
CheckTaskSched = 0

; NSCAServer - A server that listens for incoming NSCA connection and processes incoming requests.
NSCAServer = 0

; CheckLogFile - File for checking log files and various other forms of updating text files
CheckLogFile = 0

; SyslogClient - Forward information as syslog messages to a syslog server
SyslogClient = 0

; NRPEClient - NRPE client can be used both from command line and from queries to check remote systes via NRPE as well as configure the NRPE server
NRPEClient = 0

; WEBServer - A server that listens for incoming HTTP connection and processes incoming requests. It provides both a WEB UI as well as a REST API in addition to simplifying configuration of WEB Server module.
WEBServer = 0

; GraphiteClient - Graphite client can be used to submit graph data to a graphite graphing system
GraphiteClient = 0

; SMTPClient - SMTP client can be used both from command line and from queries to check remote systes via SMTP
SMTPClient = 0

; CheckWMI - Check status via WMI
CheckWMI = 1

; Scheduler - Use this to schedule check commands and jobs in conjunction with for instance passive monitoring through NSCA
Scheduler = 0

; NRPEServer - A server that listens for incoming NRPE connection and processes incoming requests.
NRPEServer = 1

; CheckSystem - Various system related checks, such as CPU load, process state, service state memory usage and PDH counters.
CheckSystem = 1

; NSClientServer - A server that listens for incoming check_nt connection and processes incoming requests.
NSClientServer = 1

; CheckExternalScripts - Execute external scripts
CheckExternalScripts = 1

; CheckHelpers - Various helper function to extend other checks.
CheckHelpers = 1

; SimpleCache - Stores status updates and allows for active checks to retrieve them
SimpleCache = 0

; CheckEventLog - Check for errors and warnings in the event log.
CheckEventLog = 1

; CheckNSCP - Use this module to check the healt and status of NSClient++ it self
CheckNSCP = 0

; CheckDisk - CheckDisk can check various file and disk related things.
CheckDisk = 1


; A list of available remote target systems
[/settings/targets]


; Configure which services has to be in which state
[/settings/system/windows/service mapping]


; A set of options to configure the real time checks
[/settings/system/windows/real-time]


; Section for system checks and system settings
[/settings/system/windows]

; DEFAULT LENGTH - Used to define the default interval for range buffer checks (ie. CPU).
default buffer length = 1h


; Section for configuring the shared session.
[/settings/shared session]

; ENABLE THE SAHRED SESSION - This is currently not added in 0.4.x
enabled = false


; Section for the PythonScripts module.
[/settings/python]


; A set of options to configure the real time checks
[/settings/logfile/real-time]

; REAL TIME CHECKING - Spawns a background thread which waits for file changes.
enabled = 0


; Configure log file properties.
[/settings/log/file]

; MAXIMUM FILE SIZE - When file size reaches this it will be truncated to 50% if set to 0 (default) truncation will be disabled
max size = 0


; A list of scripts available to run from the PythonScript module.
[/settings/python/scripts]


; Section for configuring the log handling.
[/settings/log]

; LOG LEVEL - Log level to use. Available levels are error,warning,info,debug,trace
level = info

; FILENAME - The file to write log data to. Set this to none to disable log to file.
file name = ${exe-path}/nsclient.log

; DATEMASK - The size of the buffer to use when getting messages this affects the speed and maximum size of messages you can recieve.
date format = %Y-%m-%d %H:%M:%S


; Section for simple file writer module (SimpleFileWriter.dll).
[/settings/writers/file]

; MESSAGE SYNTAX - The syntax of the message to write to the line. Can be any arbitrary string as well as include any of the following special keywords:${command} = The command name, ${host} the host, ${channel} the recieving channel, ${alias} the alias for the command, ${alias-or-command} = alias if set otherweise command, ${message} = the message data (no escape), ${result} = The result status (number).
syntax = ${alias-or-command} ${result} ${message}

; FILE TO WRITE TO - The filename to write output to.
file = output.txt

; CHANNEL - The channel to listen to.
channel = FILE


; Section for graphite passive check module.
[/settings/graphite/client]

; CHANNEL - The channel to listen to.
channel = GRAPHITE

; HOSTNAME - The host name of this host if set to blank (default) the windows name of the computer will be used.
hostname = auto


; A list of wrapped scripts (ie. scruts using a template mechanism). The template used will be defined by the extension of the script.
[/settings/external scripts/wrapped scripts]

check_mssql=check_mssql.ps1 $ARG1$

; Target definition for: default
[/settings/syslog/client/targets/default]

; TODO - 
warning severity = warning

; TODO - 
tag_syntax = NSCA

; TODO - 
severity = error

; TODO - 
ok severity = informational

; TODO - 
message_syntax = %message%

; TODO - 
facility = kernel

; TODO - 
critical severity = critical

; TODO - 
unknown severity = emergency

; TARGET ADDRESS - Target host address
address = 


; Section for external scripts configuration options (CheckExternalScripts).
[/settings/external scripts]



; 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.
timeout = 10

; SCRIPT DIRECTORY - Load all scripts in a directory and use them as commands. Probably dangerous but useful if you have loads of scripts :)
script path = 

; COMMAND ALLOW NASTY META CHARS - This option determines whether or not the we will allow clients to specify nasty (as in |`&><'"\[]{}) characters in arguments.
allow nasty characters = 1

; COMMAND ARGUMENT PROCESSING - This option determines whether or not the we will allow clients to specify arguments to commands that are executed.
allow arguments = 1


; Section for SYSLOG passive check module.
[/settings/syslog/client]

; CHANNEL - The channel to listen to.
channel = syslog

; HOSTNAME - The host name of this host if set to blank (default) the windows name of the computer will be used.
hostname = 


; A set of options to configure the real time checks
[/settings/eventlog/real-time]

; STARTUP AGE - The initial age to scan when starting NSClient++
startup age = 30m

; REAL TIME CHECKING - Spawns a background thread which detects issues and reports them back instantly.
enabled = 0

; DEBUG - Log missed records (useful to detect issues with filters) not useful in production as it is a bit of a resource hog.
debug = 0

; LOGS TO CHECK - Comma separated list of logs to check
log = application,system


; Section for configuring the crash handler.
[/settings/crash]

; SUBMIT CRASHREPORTS - Submit crash reports to nsclient.org (or your configured submission server)
submit = false

; CRASH ARCHIVE LOCATION - The folder to archive crash dumps in
archive folder = ${shared-path}/crash-dumps

; ARCHIVE CRASHREPORTS - Archive crash reports in the archive folder
archive = true

; RESTART SERVICE NAME - The url to submit crash reports to
restart target = NSCP

; RESTART - Submit crash reports to nsclient.org (or your configured submission server)
restart = true

; SUBMISSION URL - The url to submit crash reports to
submit url = https://crash.nsclient.org/post


; Section for log file checker
[/settings/logfile]


; Section for SMTP passive check module.
[/settings/SMTP/client]

; CHANNEL - The channel to listen to.
channel = SMTP


; Section for NSCA (NSCAServer) (check_nsca) protocol options.
[/settings/NSCA/server]

; PORT NUMBER - Port to use for NSCA.
port = 5667

; PERFORMANCE DATA - Send performance data back to nagios (set this to false to remove all performance data).
performance data = 1

; ENABLE SSL ENCRYPTION - This option controls if SSL should be enabled.
use ssl = 0

; ENCRYPTION - Name of encryption algorithm to use. Has to be the same as your agent i using or it wont work at all.This is also independent of SSL and generally used instead of SSL. Available encryption algorithms are: none = No Encryption (not safe) xor = XOR des = DES 3des = DES-EDE3 cast128 = CAST-128 xtea = XTEA blowfish = Blowfish twofish = Twofish rc2 = RC2 aes128 = AES aes192 = AES aes = AES serpent = Serpent gost = GOST
encryption = aes

; PAYLOAD LENGTH - Length of payload to/from the NSCA agent. This is a hard specific value so you have to "configure" (read recompile) your NSCA agent to use the same value for it to work.
payload length = 8192


; Target definition for: default
[/settings/NSCA/client/targets/default]

; ENABLE SSL ENCRYPTION - This option controls if SSL should be enabled.
use ssl = 0

; TIMEOUT - Timeout when reading/writing packets to/from sockets.
timeout = 10

; ENCRYPTION - Name of encryption algorithm to use. Has to be the same as your server i using or it wont work at all.This is also independent of SSL and generally used instead of SSL. Available encryption algorithms are: none = No Encryption (not safe) xor = XOR des = DES 3des = DES-EDE3 cast128 = CAST-128 xtea = XTEA blowfish = Blowfish twofish = Twofish rc2 = RC2 aes128 = AES aes192 = AES aes = AES serpent = Serpent gost = GOST
encryption = aes

; SSL CERTIFICATE - 
certificate = 

; ALLOWED CIPHERS - A better value is: ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH
allowed ciphers = ADH

; VERIFY MODE - 
verify mode = none

; PASSWORD - The password to use. Again has to be the same as the server or it wont work at all.
password = 

; TARGET ADDRESS - Target host address
address = 


; Section for NSClient (NSClientServer.dll) (check_nt) protocol options.
[/settings/NSClient/server]

; ENABLE SSL ENCRYPTION - This option controls if SSL should be enabled.
use ssl = 0

; PERFORMANCE DATA - Send performance data back to Nagios (set this to 0 to remove all performance data).
performance data = 1

; PORT NUMBER - Port to use for check_nt.
port = 12489


; A set of filters to use in real-time mode
[/settings/system/windows/real-time/checks]


; Section for NSCA passive check module.
[/settings/NSCA/client]

; HOSTNAME - The host name of the monitored computer. Set this to auto (default) to use the windows name of the computer.  auto	Hostname ${host}	Hostname ${host_lc} Hostname in lowercase ${host_uc}	Hostname in uppercase ${domain}	Domainname ${domain_lc}	Domainname in lowercase ${domain_uc}	Domainname in uppercase 
hostname = auto

; CHANNEL - The channel to listen to.
channel = NSCA


; Section for NRPE (NRPEServer.dll) (check_nrpe) protocol options.
[/settings/NRPE/server]

; ENABLE SSL ENCRYPTION - This option controls if SSL should be enabled.
use ssl = 1

; ALLOW INSECURE CHIPHERS and ENCRYPTION - Only enable this if you are using legacy check_nrpe client.
insecure = 1

; COMMAND ALLOW NASTY META CHARS - This option determines whether or not the we will allow clients to specify nasty (as in |`&><'"\[]{}) characters in arguments.
allow nasty characters = 1

; COMMAND ARGUMENT PROCESSING - This option determines whether or not the we will allow clients to specify arguments to commands that are executed.
allow arguments = 1

; PORT NUMBER - Port to use for NRPE.
port = 5666

; EXTENDED RESPONSE - Send more then 1 return packet to allow response to go beyond payload size (requires modified client if legacy is true this defaults to false).
extended response = 0

timeout = 10

; Target definition for: default
[/settings/NRDP/client/targets/default]

; SENDER - Sender of email message
sender = nscp@localhost

; RECIPIENT - Recipient of email message
recipient = nscp@localhost

; TARGET ADDRESS - Target host address
address = 

; TEMPLATE - Template for message data
template = Hello, this is %source% reporting %message%!

; TIMEOUT - Timeout when reading/writing packets to/from sockets.
timeout = 30


; Section for SMTP passive check module.
[/settings/NRDP/client]

; HOSTNAME - The host name of this host if set to blank (default) the windows name of the computer will be used.
hostname = auto

; CHANNEL - The channel to listen to.
channel = NRDP


; Target definition for: default
[/settings/NRPE/client/targets/default]

; SSL CERTIFICATE KEY - Key for the SSL certificate
certificate key = 

; TARGET ADDRESS - Target host address
address = 

; Insecure legacy mode - Use insecure legacy mode to connect to old NRPE server
insecure = 

; VERIFY MODE - What to verify default is non, to validate remote certificate use remote-peer
verify mode = none

; PAYLOAD LENGTH - Length of payload to/from the NRPE agent. This is a hard specific value so you have to "configure" (read recompile) your NRPE agent to use the same value for it to work.
payload length = 1024

; ENABLE SSL ENCRYPTION - This option controls if SSL should be enabled.
use ssl = 1

; TIMEOUT - Timeout when reading/writing packets to/from sockets.
timeout = 30

; SSL CERTIFICATE - The ssl certificate to use to encrypt the communication
certificate = 


; Section for WEB (WEBServer.dll) (check_WEB) protocol options.
[/settings/WEB/server]

; PORT NUMBER - Port to use for WEB server.
port = 8443s

; CERTIFICATE - Ssl certificate to use for the ssl server
certificate = ${certificate-path}/certificate.pem


; Target definition for: default
[/settings/SMTP/client/targets/default]

; SENDER - Sender of email message
sender = nscp@localhost

; TARGET ADDRESS - Target host address
address = 

; TEMPLATE - Template for message data
template = Hello, this is %source% reporting %message%!

; TIMEOUT - Timeout when reading/writing packets to/from sockets.
timeout = 30

; RECIPIENT - Recipient of email message
recipient = nscp@localhost


; Files to be included in the configuration
[/includes]


; Section for the EventLog Checker (CheckEventLog.dll).
[/settings/eventlog]

; BUFFER_SIZE - The size of the buffer to use when getting messages this affects the speed and maximum size of messages you can recieve.
buffer size = 131072

; LOOKUP NAMES - Lookup the names of eventlog files
lookup names = 1

; SYNTAX - Set this to use a specific syntax string for all commands (that don't specify one).
syntax = 

; DEBUG - Log more information when filtering (useful to detect issues with filters) not useful in production as it is a bit of a resource hog.
debug = 0


; Section for NRPE active/passive check module.
[/settings/NRPE/client]

; CHANNEL - The channel to listen to.
channel = NRPE


; Section for the Scheduler module.
[/settings/scheduler/schedules]


; A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>
[/settings/external scripts/scripts]

;check_mssql3 = check_mssql.ps1 
test_cmd=cmd /c "dir c:\\" 
;check_mssql2=cmd /c echo scripts\check_mssql.ps1 ; exit($lastexitcode) | powershell.exe -ExecutionPolicy Bypass -command - 
check_sql = cscript.exe //T:30 //NoLogo scripts\\lib\\wrapper.vbs check_sqlJobs.vbs

; default - Alias for default. To configure this item add a section called: /settings/external scripts/scripts/default
default = 


; A list of aliases available.
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)
[/settings/external scripts/alias]

; alias_sched_all - Alias for alias_sched_all. To configure this item add a section called: /settings/external scripts/alias/alias_sched_all
alias_sched_all = check_tasksched show-all "syntax=${title}: ${exit_code}" "crit=exit_code ne 0"

; alias_file_size - Alias for alias_file_size. To configure this item add a section called: /settings/external scripts/alias/alias_file_size
alias_file_size = check_files "path=$ARG1$" "crit=size > $ARG2$" "top-syntax=${list}" "detail-syntax=${filename] ${size}" max-dir-depth=10

; alias_process_hung - Alias for alias_process_hung. To configure this item add a section called: /settings/external scripts/alias/alias_process_hung
alias_process_hung = check_process "filter=is_hung" "crit=count>0"

; alias_process - Alias for alias_process. To configure this item add a section called: /settings/external scripts/alias/alias_process
alias_process = check_process "process=$ARG1$" "crit=state != 'started'"

; alias_service_ex - Alias for alias_service_ex. To configure this item add a section called: /settings/external scripts/alias/alias_service_ex
alias_service_ex = check_service "exclude=Net Driver HPZ12" "exclude=Pml Driver HPZ12" exclude=stisvc

; alias_event_log - Alias for alias_event_log. To configure this item add a section called: /settings/external scripts/alias/alias_event_log
alias_event_log = check_eventlog

; alias_volumes_loose - Alias for alias_volumes_loose. To configure this item add a section called: /settings/external scripts/alias/alias_volumes_loose
alias_volumes_loose = check_drivesize

; alias_volumes - Alias for alias_volumes. To configure this item add a section called: /settings/external scripts/alias/alias_volumes
alias_volumes = check_drivesize

; alias_disk - Alias for alias_disk. To configure this item add a section called: /settings/external scripts/alias/alias_disk
alias_disk = check_drivesize

; alias_cpu_ex - Alias for alias_cpu_ex. To configure this item add a section called: /settings/external scripts/alias/alias_cpu_ex
alias_cpu_ex = check_cpu "warn=load > $ARG1$" "crit=load > $ARG2$" time=5m time=1m time=30s

; alias_file_age - Alias for alias_file_age. To configure this item add a section called: /settings/external scripts/alias/alias_file_age
alias_file_age = check_files "path=$ARG1$" "crit=written > $ARG2$" "top-syntax=${list}" "detail-syntax=${filename] ${written}" max-dir-depth=10

; alias_process_stopped - Alias for alias_process_stopped. To configure this item add a section called: /settings/external scripts/alias/alias_process_stopped
alias_process_stopped = check_process "process=$ARG1$" "crit=state != 'stopped'"

; alias_service - Alias for alias_service. To configure this item add a section called: /settings/external scripts/alias/alias_service
alias_service = check_service

; default - Alias for default. To configure this item add a section called: /settings/external scripts/alias/default
default = 

; alias_cpu - Alias for alias_cpu. To configure this item add a section called: /settings/external scripts/alias/alias_cpu
alias_cpu = check_cpu

; alias_mem - Alias for alias_mem. To configure this item add a section called: /settings/external scripts/alias/alias_mem
alias_mem = check_memory

; alias_process_count - Alias for alias_process_count. To configure this item add a section called: /settings/external scripts/alias/alias_process_count
alias_process_count = check_process "process=$ARG1$" "warn=count > $ARG2$" "crit=count > $ARG3$"

; alias_up - Alias for alias_up. To configure this item add a section called: /settings/external scripts/alias/alias_up
alias_up = check_uptime

; alias_sched_task - Alias for alias_sched_task. To configure this item add a section called: /settings/external scripts/alias/alias_sched_task
alias_sched_task = check_tasksched show-all "filter=title eq '$ARG1$'" "detail-syntax=${title} (${exit_code})" "crit=exit_code ne 0"

; alias_disk_loose - Alias for alias_disk_loose. To configure this item add a section called: /settings/external scripts/alias/alias_disk_loose
alias_disk_loose = check_drivesize

; alias_sched_long - Alias for alias_sched_long. To configure this item add a section called: /settings/external scripts/alias/alias_sched_long
alias_sched_long = check_tasksched "filter=status = 'running'" "detail-syntax=${title} (${most_recent_run_time})" "crit=most_recent_run_time < -$ARG1$"


; Target definition for: default
[/settings/graphite/client/targets/default]

; PATH FOR VALUES - Path mapping for metrics
path = system.${hostname}.${check_alias}.${perf_alias}

; TARGET ADDRESS - Target host address
address = 


; Modules written in dotnet/CLR
[/modules/dotnet]


; Add counters to check
[/settings/system/windows/counters]


; A set of filters to use in real-time mode
[/settings/logfile/real-time/checks]


; Section for simple cache module (SimpleCache.dll).
[/settings/cache]

; CHANNEL - The channel to listen to.
channel = CACHE

; PRIMARY CACHE INDEX - Set this to the value you want to use as unique key for the cache. Can be any arbitrary string as well as include any of the following special keywords:${command} = The command name, ${host} the host, ${channel} the recieving channel, ${alias} the alias for the command, ${alias-or-command} = alias if set otherweise command, ${message} = the message data (no escape), ${result} = The result status (number).
primary index = ${alias-or-command}


; Section for the Scheduler module.
[/settings/scheduler]

; THREAD COUNT - Number of threads to use.
threads = 5


; A list of templates for wrapped scripts.
%SCRIPT% will be replaced by the actual script an %ARGS% will be replaced by any given arguments.
[/settings/external scripts/wrappings]


; BATCH FILE WRAPPING - 
bat = scripts\\%SCRIPT% %ARGS%

; VISUAL BASIC WRAPPING - 
vbs = cscript.exe //T:30 //NoLogo scripts\\lib\\wrapper.vbs %SCRIPT% %ARGS%

; POWERSHELL WRAPPING - 
ps1 = cmd /c echo scripts\\%SCRIPT% %ARGS% ; exit($lastexitcode) | powershell.exe -ExecutionPolicy Bypass -command -  



; A set of filters to use in real-time mode
[/settings/eventlog/real-time/filters]

; default - Filter for default. To configure this item add a section called: /settings/eventlog/real-time/filters/default
default = 


[/paths]

; Path for shared-path - 
shared-path = c:\Program Files\NSClient++

; Path for exe-path - 
exe-path = c:\Program Files\NSClient++

; Path for crash-folder - 
crash-folder = c:\Program Files\NSClient++

; Path for certificate-path - 
certificate-path = ${shared-path}/security

; Path for base-path - 
base-path = c:\Program Files\NSClient++

; Path for module-path - 
module-path = ${shared-path}/modules
User avatar
tgriep
Madmin
Posts: 9177
Joined: Thu Oct 30, 2014 9:02 am

Re: NRPE Error: returns 0 byte

Post by tgriep »

Can you post the Powershell script here so we can see what it is doing?
I bet the issue is that the script is failing and not returning valid data.
Be sure to check out our Knowledgebase for helpful articles and solutions!
sajid4u2c
Posts: 46
Joined: Thu Mar 15, 2018 10:55 am

Re: NRPE Error: returns 0 byte

Post by sajid4u2c »

Here is the full plugin code.

Code: Select all

<#
  .SYNOPSIS
   script for nagios to check SQL DataBases , Connection Time, Jobs.	
  .DESCRIPTION
   Auther Yossi Bitton yossi@edp.co.il
   Date: November 2016   
  .EXAMPLE
	.\check_mssql.ps1 
   version 1.0.4	
	
   for Nagios NRPE edit NSC.ini or nsclient.ini and add the following line under section:
	[Wrapped Scripts] 
	 check_mssql=check_mssql.ps1 $ARG1$
	
	[Script Wrappings]
	ps1 = cmd /c echo scripts\%SCRIPT% %ARGS%; exit($lastexitcode) | powershell.exe -ExecutionPolicy Bypass -command -
	
	from nagios run:
	./check_nrpe -H <MSSQL IP Address> -c check_mssql -a '-CheckType DBStatus -Exclude DB01,DB03' 
	or 
	./check_nrpe -H <MSSQL IP Address> -c check_mssql -a 'DBStatus'
	./check_nrpe -H <MSSQL IP Address> -c check_mssql -a 'ConTime'
	./check_nrpe -H <MSSQL IP Address> -c check_mssql -a 'Jobs'
	if no instance specify the script check the default instance (COMPUTERNAME)
	to monitor specify instance add -InstanceName <Instance Name>.	
#>

[CmdletBinding()]
Param(
	[parameter(Mandatory=$true,Position=1)] 
	[ValidateSet("DBStatus", "ConTime", "Jobs")] 
	[String]$CheckType ,
	[parameter(Mandatory=$false,Position=2)]
	[String[]]$InstanceName  ,
	[parameter(Mandatory=$false,Position=3)]
	[boolean]$DebugMode ,
	[parameter(Mandatory=$false,Position=4)]
	[String[]]$Exclude
)
begin {


Function Print_Debug ($msg){
	if ($DebugMode) {
		Write-Host "$msg"
	}

}
	
#Connect to sql server 
function Connect_To_Sql ($instance) {
	Print_Debug "Function:	Connect_To_Sql."
	$retCode = $false
	$sqlObj = ""
	try {
		Print_Debug "Trining to connect to $instance ..."
		$sqlObj = New-Object "Microsoft.SqlServer.Management.Smo.Server" $instance
		if($sqlObj.Version -ne $null -or $sqlObj.Databases -ne $null )  {
			$desc = "Connecting to SQL server $instance completed"
			$retCode = $true
		}else {
			$desc = "Failed to Connect to SQL server $instance"	
		}
	}catch{
		$desc = $_.Exception.Message	
		Print_Debug $desc
	}
Print_Debug $desc
return $retCode, $desc , $sqlObj 
	
}
	

#Connect to sql server 
	function SQL_Connection_Time ($instance) {
		Print_Debug "SQL_Connection_Time..."
		$retCode = $unknown
		$desc = "an error has occurred when trying to connect to the SQL server"
		$perfData = ""
		try {
			$connTime = (Measure-Command { $sqlObj = New-Object "Microsoft.SqlServer.Management.Smo.Server"  $instance}).totalseconds 
		}catch{
			$desc = $_.Exception.Message	
			Print_Debug $desc
		}
		
		$sqlVersion =  $sqlObj.Version
		if($sqlObj.Version -ne $null -or $sqlObj.Databases -ne $null ) {
			$perfData = "|'Connect Time'=" + $connTime + ";$timeToConnectWarn;$timeToConnectCrit;$connTime"
			if ($connTime -lt $timeToConnectWarn) {
				$desc = "$instance Connect time=$connTime seconds, Version $sqlVersion"
				$retCode = $ok
			}elseif ($connTime -gt $timeToConnectCrit){
				$desc = "$instance Connect took too long, time=$connTime seconds, Version $sqlVersion"
				$retCode = $critical
			}elseif ($connTime -lt $timeToConnectCrit -and $connTime -gt $timeToConnectWarn ){
				$desc = "$instance Connect took too long, time=$connTime seconds, Version $sqlVersion"
				$retCode = $warning
			}
		}else {
			$desc = "Failed to Connect to SQL server $instance [$connTime seconds]"
			$retCode = $critical
		}
	
return $retCode, "$desc$perfData"
	}

# Load SQL power shell module	
	function Load_Sql_Smo () {
	Print_Debug "Function: Load_Sql_Smo. "
	$retCode = $unknown
	$desc = ""
	try {
		if ([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")){
			$retCode = $true
			$desc = "SMO module load successful" 
		}
	}catch {
		$desc = $_.Exception.Message
	}
	Print_Debug $desc
	return $retCode , $desc
}

#Get SQL jobs status 
	function Get_Jobs_Status($sqlObj) {
		$retCode = $unknown
		$desc = "an error has occurred when trying to get sql jobs"
		$totalJobCount = $sqlObj.JobServer.Jobs.Count;
		if ($totalJobCount -gt 0){
			$failedCount = 0;
			$successCount = 0;
			# loop in all jobs to check last status
			$totalJobCount =0
			$desc = $null
			foreach($job in $sqlObj.JobServer.Jobs)
			{
				$skipJob = $False
				$jobName = $job.Name;
				$jobEnabled = $job.IsEnabled;
				$LastRunDate = $job.LastRunDate
				$jobLastRunOutcome = $job.LastRunOutcome;
				$HasSchedule = $job.HasSchedule
				if($jobEnabled -eq $true -and $HasSchedule -eq $True) {
					$totalJobCount+=1
					if($Exclude -ne $null){
						Print_Debug "Exclude list=$Exclude"
						foreach($ex in $Exclude) {
							if ($jobName -eq $ex) {
								$skipJob = $True
								break
							}
						}
					}	
					
					# if job failed count failed jobs
					if($jobLastRunOutcome -eq "Failed" -and $skipJob -eq $False ){
						$failedCount += 1;
						$desc += "Job: $jobName=$jobLastRunOutcome Date: $LastRunDate. " 
					}elseif($jobLastRunOutcome -eq "Succeeded") {
						$successCount += 1;
					}
				}else 
				{
					Print_Debug "Job $jobName HasSchedule = $HasSchedule "
				}
			}
			# Found failed job/s
			if 	($failedCount -gt 0) {
				$desc = "Total failed: $failedCount. $desc"
				$retCode = $critical 
			}else{
				if($Exclude -ne $Null) {
					$desc = "All SQL jobs are completed successful, Total:($successCount) [Excluded Jobs: $Exclude]"
				}else{
					$desc = "All SQL jobs are completed successful, Total:($successCount)"
				}		
				$retCode = $ok 
			}
		}else{
			$desc = "No jobs found in SQL server $sqlObj"
			$retCode = $ok
		}
	return $retCode , $desc
	}

# Check if all Databases are in on line mode. 	
	function Get_DataBase_Status ($sqlObj , $instance) {
	Print_Debug "Function: Get_DataBase_Status"
	$retCode = $unknown
	$desc = ""
	$failedDBCount = 0;
	$successDBCount = 0;
	$totalDb = $sqlObj.Databases.Count
	foreach($db in $sqlObj.Databases)
	{
		$skipDB = $False
		$dbStatus = $db.Status
		$dbName = $db.Name
		if($Exclude -ne $null){
			Print_Debug "Exclude list=$Exclude"
			foreach($ex in $Exclude) {
				if ($dbName -eq $ex) {
					$skipDB = $True
					break
				}
			}
		}	
		Print_Debug "SkipDB = $SkipDB"
		if($dbStatus -ne "Normal" -and $skipDB -eq $False) {
			$failedDBCount +=1;
			$desc += "$dbName Is: $dbStatus.`n" 
		}
	}
	if 	($failedDBCount -gt 0) {
		$desc = "$instance Total failed: $failedDBCount/$totalDb $desc "
		if ($Exclude -ne $null) {
			$desc = "$instance Total failed: $failedDBCount/$totalDb $desc "
		}
		$retCode = $critical
	}else{
		if($Exclude -ne $Null) {
			$desc = "$instance All Databases are online. [Total DataBases: $totalDb] [Excluded DB: $Exclude]"
		}else{
			$desc = "$instance All Databases are online. [Total DataBases: $totalDb]"
		}		
		$retCode = $ok
	}
	Print_Debug $desc	
	return $retCode , $desc	
	}

#Close End Section
}


	
process {
	$ok=0
	$warning=1
	$critical=2
	$unknown=3
	$retCode = $unknown
	$Server = $env:COMPUTERNAME
	$timeToConnectCrit=5
	$timeToConnectWarn=3

	$AllInstance = @()
	if ($InstanceName -ne $null) {
		$InstanceNameReplaced = $InstanceName -Replace(' ' , '')
		Print_Debug $InstanceNameReplaced
		foreach ($ins in $InstanceNameReplaced) {
			Print_Debug $ins
			$AllInstance +="$Server\$ins" 
		 }
	}else{
		$AllInstance += $Server
	}
	
	Print_Debug $AllInstance
	Print_Debug $AllInstance.Count
	
	# Load SQL module
	$smoLoad , $desc = Load_Sql_Smo						
	if ($smoLoad -eq $true) {
		$TotalInstance = $AllInstance.Count
		Print_Debug "TotalInstance=$TotalInstance"
		$TotalOkFound = 0 
		Print_Debug "TotalOkFound=$TotalOkFound"
		$i = 0
		foreach($instance in $AllInstance){	
			$i +=1
			Print_Debug  "Current Instance is: $i : $instance" 
			$sqlConn ,$desc ,$sqlObj = Connect_To_Sql $instance   
			if ($sqlConn -eq $true) {
				$desc = $null
				Switch($CheckType) {
					"DBStatus" 
					{
						$check_status, $check_desc = Get_DataBase_Status $sqlObj $instance
						Print_Debug "Current Instance Name=$check_desc"
						$sum_cehck_desc += "$check_desc`n"
						Print_Debug "Status of $instance is $check_desc"
					}
					"ConTime" 
					{
						$check_status ,$check_desc = SQL_Connection_Time $instance
						Print_Debug "ConTime=$check_status, Status=$check_desc"
						$sum_cehck_desc += "$check_desc`n"
						Print_Debug "Status of $instance is $check_desc"
					}
					"Jobs"
					{
						$check_status ,$check_desc  = Get_Jobs_Status $sqlObj
						Print_Debug "ConTime=$check_status, Status=$check_desc"
						$sum_cehck_desc += "$check_desc`n"
						Print_Debug "Status of $instance is $check_desc"
					}
				}
				if($check_status -eq $ok) {
					$TotalOkFound +=1
					Print_Debug "Total Ok Found =$TotalOkFound"
				}else{
					$sum_cehck_desc  += "$check_desc`n"
				}
			}else {
				$sum_cehck_desc += "$desc`n"
			}
			
		}
		
		Print_Debug "Total Instance OK: $TotalOkFound/$TotalInstance"
		if($TotalOkFound -eq $TotalInstance) { 
			Print_Debug "Total Ok Instance is equal to Total Instance, Exit OK"
			$desc = $sum_cehck_desc
			$retCode = $ok
		}else{
			Print_Debug "Total Ok Instance is NOT equal to Total Instance, Exit ERROR"
			$retCode = $critical
			$desc = $sum_cehck_desc
		}
	}
}

end {
switch ($retCode)
		{
			0 {$msgPrefix="OK"}
			1 {$msgPrefix="Warning"}
			2 {$msgPrefix="Critical"}
			3 {$msgPrefix="Unknown"}
				
		}	
	write-host $msgPrefix":" $desc $perfData
	exit $retCode
}
User avatar
tgriep
Madmin
Posts: 9177
Joined: Thu Oct 30, 2014 9:02 am

Re: NRPE Error: returns 0 byte

Post by tgriep »

The plugin has been updated from the version you posted so get the latest version of the powershell script at this link and try it to see if the issue is resolved after updating it.
https://github.com/yosbit/nagios-plugin ... k_mssql.md

After that, try logging in to the MSSQL server and run the script out of Powershell to see if it works.

You should see something similar to this.

Code: Select all

./check_mssql.ps1 DBStatus
OK: All databases in all sql instances are in normal state. Total Instances=1 Total Databases=4
SQLEXPRESS master=Normal, model=Normal, msdb=Normal, tempdb=Normal, [4].
If that works, try running the check_nrpe command like this example on the Nagios server and see if it works.

Code: Select all

/usr/local/nagios/libexec/check_nrpe -H sqlserver -c check_mssql -a DBStatus
OK: All databases in all sql instances are in normal state. Total Instances=1 Total Databases=4
SQLEXPRESS master=Normal, model=Normal, msdb=Normal, tempdb=Normal, [4].
Be sure to check out our Knowledgebase for helpful articles and solutions!
sajid4u2c
Posts: 46
Joined: Thu Mar 15, 2018 10:55 am

Re: NRPE Error: returns 0 byte

Post by sajid4u2c »

Thanks for the new plugin update :)

I have used new plugin the suggested commands at both the DB server and Nagios servers.

Commands worked well inside the DB server and got the required output.

However when I execute the command from Nagios terminal , i still get the errro

Code: Select all

" 0 bytes received. Check remote server logs"
The nsclient.log still shows

Code: Select all

"error:D:\source\nscp\include\socket/connection.hpp:149: Failed to send data: The file handle supplied is not valid" 
error :(
User avatar
tgriep
Madmin
Posts: 9177
Joined: Thu Oct 30, 2014 9:02 am

Re: NRPE Error: returns 0 byte

Post by tgriep »

Edit the nsclient.ini file and remove this line from the nsclient.ini file

Code: Select all

check_mssql=check_mssql.ps1 $ARG1$
Under this section

Code: Select all

[/settings/external scripts/scripts]
Put this line in.

Code: Select all

check_mssql = cmd /c echo scripts\check_mssql.ps1 $ARG1$ ; exit($lastexitcode) | powershell.exe -ExecutionPolicy Bypass  -command -	

Make sure the powershell script is in the following folder.

Code: Select all

C:\Program Files\NSClient++\scripts
You may want to increase the timeout for the external scripts. Under this section

Code: Select all

[/settings/external scripts]
Change this from

Code: Select all

timeout = 10
to

Code: Select all

timeout = 60
Save the file and restart the NSClient++ agent.

Test the command from the Nagios server.

When you ran the powershell script on the windows server, how long did it take to run?
If it takes longer than 60 seconds then the timeout setting above has to be increased further as well as the time out value for the check_nrpe plugin and the service timeout settings in the nagios.cfg file so the plugin and nagios will not timeout and generate that error.
Be sure to check out our Knowledgebase for helpful articles and solutions!
sajid4u2c
Posts: 46
Joined: Thu Mar 15, 2018 10:55 am

Re: NRPE Error: returns 0 byte

Post by sajid4u2c »

Thanks @tgriep.

Seems it was indeed the time-out issue .
Increased the time-out values as suggested and able to run the commands.
Thanks, please close the thread. :)
Locked