2010/11/16

Nagios: Restart a Windows Failed Services (cmd)

CURRENT CONFIGURATION: Linux OpenSuSe, Nagios 3.0.2, NRPE; Windows 2003 x64 server, NSClient++ 0.3.8.76

OBJECTIVE: Building a Self-Healing Network

ISSUE: Need some script to Restart failed Windows Services by Nagios Client

SOLUTION:
I created and tested win_service_restart.cmd batch file on Microsoft Windows 2003 servers.

--- Start of code ---

@echo off
:: *****************************************************************************
:: File:    win_service_restart.cmd
:: Author:  Vadims Zenins http://vadimszenins.blogspot.com
:: Version: 1.07
:: Date:    16/11/2010 12:28:45
:: Windows Failed Service restart batch file for Nagios Event Handler
::
::  Copy win_service_restart.cmd to \NSClient++\scripts\ folder.
::
:: Nagios commands.cfg:
:: define command{
::        command_name    win_service_restart
::        command_line    $USER1$/check_nrpe -H $HOSTADDRESS$ -p 5666 -c win_service_restart -a "$SERVICEDESC$" $SERVICESTATE$ $SERVICESTATETYPE$ $SERVICEATTEMPT$
::        }
::
:: Nagios template-services_common-win.cfg
:: define service{
::         name                    generic-service-win-wuauserv
::         service_description     wuauserv
::         display_name            Automatic Updates
::         event_handler           win_service_restart
::         event_handler_enabled   1
::         check_command           check_nt!SERVICESTATE!-d SHOWALL -l $SERVICEDESC$
::         }
::
:: NSCLIENT++ version 0.3.8 NSC.ini:
::   [Settings]
::   allowed_hosts=192.168.1.1/32  ; your Nagios server IP
::   [NRPE]
::   allow_arguments=1
::   allow_nasty_meta_chars=1
::   [Script Wrappings]
::   cmd=scripts\%SCRIPT% %ARGS%
::   [External Script]
::   allow_arguments=1
::   allow_nasty_meta_chars=1
::   [External Scripts]
::   command[win_service_restart]=scripts\win_service_restart.cmd "$ARG1$" $ARG2$ $ARG3$ $ARG4$
::
::
:: Additional examples on http://vadimszenins.blogspot.com/2008/12/nagios-restart-windows-failed-services.html
::
:: Tested platform:
:: Windows 2003 R2 x64 SP2, Nagios 3.2.0, NSClient++ 0.3.8.76
::
:: Version 1.07 revision:
:: Description is changed for NSCLIENT++ version 0.3.8 NSC.ini
:: Version 1.06 revision:
:: Description is changed for NSCLIENT++ version 0.3.8 NSC.ini
:: Version 1.05 revision:
:: Logging changes, stop and start services commands nave changed. Logs examples added.
:: Version 1.04 revision:
:: Double restart of the servise is fixed
:: Version 1.03 revision:
:: Description is changed
:: Version 1.02 revision:
:: @NET changed to @SC
:: Version 1.01 revision:
:: Service name's with spase problem is fixed
::
:: This code is made available as is, without warranty of any kind. The entire
:: risk of the use or the results from the use of this code remains with the user.
:: *****************************************************************************

::echo 1: %1    2: %2    3: %3    4: %4

@SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
:: Grab a file name and extension only
SET SCRIPTNAME=%~nx0
:: Replace "
SET SCRIPTNAME=%SCRIPTNAME:"=%
SET LOGDIR=C:\tools\logs
SET SERVICENAME=%1
:: Replace "
SET SERVICENAME1=%SERVICENAME:"=%
SET LOGFILE=%1
SET LOGFILE=%LOGFILE:"=%
:: Replace space by _
SET LOGFILE=%LOGFILE: =_%
SET LOGFILE=%LOGDIR%\%LOGFILE%.log

if "%SERVICENAME1%"=="" SET LOGFILE=%LOGDIR%\NO_SERVICENAME.log
::@echo servicename:  %SERVICENAME%
::@echo logfile: %LOGFILE%
::@echo SERVICENAME1: %SERVICENAME1%

:: =============================================================================

if not exist %LOGDIR% md %LOGDIR%
echo. >>%LOGFILE%
echo =============================================================================  >>%LOGFILE%
echo %DATE% %TIME% %SCRIPTNAME% has started >>%LOGFILE%
echo =============================================================================  >>%LOGFILE%

@if "%SERVICENAME1%"=="" goto usage
@if "%SERVICENAME1%"=="/?" goto usage
@if "%SERVICENAME1%"=="-?" goto usage

@echo Variables 1: %1   2: %2   3: %3   4: %4 >>%LOGFILE%

@SC query %SERVICENAME% >>%LOGFILE%

@SC query %SERVICENAME% | FIND /I "RUNNING" >>%LOGFILE%
if .%ERRORLEVEL%.==.0. (
    SET RETURN=Service %SERVICENAME% is running
    goto END
)

:RESTART
@echo %DATE% %TIME% Restarting %SERVICENAME% services... >>%LOGFILE%
@SC stop %SERVICENAME% >>%LOGFILE% 2>&1
@sleep 2
SET RETURN=Service %SERVICENAME% start pending
@SC start %SERVICENAME% | FIND /I "FAILED"
if .%ERRORLEVEL%.==.0. (
    SET RETURN=Start Service %SERVICENAME% FAILED
    @SC start %SERVICENAME% >>%LOGFILE% 2>&1
    goto END
)
@sleep 5
@SC query %SERVICENAME% | FIND /I "RUNNING"
if .%ERRORLEVEL%.==.0. (
    SET RETURN=Service %SERVICENAME% has started
    @SC query %SERVICENAME% >>%LOGFILE%
    goto END
)
@goto end

:USAGE
@echo Usage: >>%LOGFILE%
@echo  win_service_restart "^" ^ ^ ^ >>%LOGFILE%
@echo  ^ is "Service name", do not mix with "Display name" >>%LOGFILE%
@echo  ^, ^ and ^ are optional >>%LOGFILE%
::exit 128

:END
echo %DATE% %TIME% %SCRIPTNAME% has finished with code >>%LOGFILE%
echo %RETURN% >>%LOGFILE%
@echo %SCRIPTNAME%: %RETURN%
exit 0

--- End of code ---

Additional examples:

template-services_common-win.cfg
define service{
name generic-service-win-backup-agent
service_description BackupExecAgentAccelerator
display_name Backup Exec Remote Agent
event_handler win_service_restart
event_handler_enabled 1
check_command check_nt!SERVICESTATE!-d SHOWALL -l $SERVICEDESC$
register 0
}

services_common-win.cfg
define service{
use generic-service-win-backup-agent,generic-service-office
hostgroup_name winsrv-office ; Assign group of servers
host_name !SERVER11,!SERVER12 ; use this to exclude some servers or delete this row
}

group_windows.cfg
define hostgroup{
hostgroup_name winsrv-office ; The name of the hostgroup
alias Office Servers
}

host-server01.cfg
define host{
use windows-server ; Inherit default values from a template
host_name server01 ; The name we're giving to this host
alias server 01 ; A longer name associated with the host
hostgroups winsrv-office ; Group of servers
address 192.168.1.1 ; IP address of the host
}


DOWNLOADS:
Download the script from exchange.nagios.org
Download the script latest version from mirror.
 
md5: dbf0663a9e6648886eb8015cee8c9ce0 *win_service_restart.zip

Download the script previous version 1.05 from mirror. md5: 8b90ba7654227f1bf07c694368843b9

Download the script previous version 1.04 from mirror. md5: fd00753533e5fb655d824c3bf1d36d4

2010/03/30

Exchange 2007 vs Google Mail Premier Edition

CURRENT CONFIGURATION: Company has Exchange 2007 and Blackberry Servers

OBJECTIVE: Compare technical possibilities with Google Email (gmail) Premier Edition for small and middle business, especial from email administration point of view.

Read a document.

SOLUTION: If you have Microsoft Exchange implemented, stay where you are. 
If I have either to upgrade Microsoft Exchange or implement email solution from scratch I will discuss with manager email confidentiality and requirements. If confidentiality does not have the highest mark and company does not have branch in China I will suggest go with Google Apps Premier Edition.

2010/03/09

MSSQL 2005 procedure a file move rename

CURRENT CONFIGURATION: MSSQL server 2005

OBJECTIVE: Move or rename a file from MSSQL

SOLUTION:
I wrote SQL procedure. You can change destination database to whatever you want.
USE master
GO

-- set required options
EXEC sp_configure 'show advanced options',1
RECONFIGURE
GO
EXEC sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO

USE [sysman]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dba_file_move_rename]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[dba_file_move_rename]
GO

CREATE PROCEDURE [dbo].[dba_file_move_rename]
    @OldFilePath    nvarchar(512),
    @NewFilePath    nvarchar(512),
    @send_email_proc  nvarchar(256),
    @log int = 2
AS
-- *****************************************************************************
-- Author:  Vadim Zenin http://vadimszenins.blogspot.com
-- Version:    1.00
-- Date:      10/12/2009 18:37:34
-- Procedure for file move or rename
--
-- Usage:
-- In batch file: sqlcmd -E -dsysman -Q"EXEC sysman..dba_file_move_rename 'C:\temp\oldfile.txt', 'C:\temp\newile.txt', 'send_email', 1" >>%LOGFILE%
--
-- Parametrs:
-- @OldFilePath example: 'C:\temp\oldfile.txt'
-- @NewFilePath example: 'C:\temp\newile.txt'
-- @send_email_proc example: 'send_email'
-- @log (0 - none, 1 - minimum, 2 - standard(default), 4 - debug) optinal
--
-- Tested platform:
-- MS SQL 2005
--
-- Version 1.00 revision:
--
--
-- This code is made available as is, without warranty of any kind. The entire
-- risk of the use or the results from the use of this code remains with the user.
-- *****************************************************************************

DECLARE
    @procname        nvarchar(256),
    @fso            int,
    @hr              int,
    @sqlcmd            nvarchar(600),
    @email_subj        nvarchar(255),
    @email_body        nvarchar(3000)

-- Get current stored procedure name
SELECT @procname = OBJECT_NAME(@@PROCID)
IF @log > 1
begin
    PRINT RTRIM(CAST(GETDATE() AS NVARCHAR(30))) + ' ' + @procname + ' procedure has started';
    PRINT N'The Database Engine instance ' + RTRIM(@@SERVERNAME) + N' is running SQL Server build '
    + RTRIM(CAST(SERVERPROPERTY(N'ProductVersion ') AS NVARCHAR(128)));
end
IF @log > 2
BEGIN
  PRINT 'Parametr 1: ' + @OldFilePath;
  PRINT 'Parametr 2: ' + @NewFilePath;
  PRINT 'Parametr 3: ' + @send_email_proc;
  PRINT 'Parametr 4: ' + RTRIM(@log);
END

-- Check requrements
If not exists (Select * from dbo.sysobjects where xtype='p' and name=@send_email_proc)
BEGIN
    SELECT @email_body = N'!? Stored procedure sysman..' + @send_email_proc + ' does not exist'
    IF @log >= 0
    PRINT @email_body
    RAISERROR (@email_body,16,1) with log
END

--------------------------------------------------------------------------------
-- Main procedure
--------------------------------------------------------------------------------

SET @hr = 0

-- Creating File System Object
EXEC @hr=sp_OACreate 'Scripting.FileSystemObject',@fso OUT
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error creating File System Object.'+ @procname
  SELECT    @email_body = 'Error creating File System Object. Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      PRINT N' Sending failure email notification with subject: '
      PRINT @email_subj
    END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END

EXECUTE @hr=sp_OAMethod @fso, 'MoveFile', null, @OldFilePath, @NewFilePath
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error moving or renaming File.' + @procname
  SELECT    @email_body = ' Error moving or renaming File from ' + @OldFilePath +
      ' to ' + @NewFilePath + ' Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      Print N' Sending failure email notification with subject: '
      Print @email_subj
  END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END
else
begin
    IF @log > 0
      Print N'Moving or renaming File from ' + @OldFilePath + ' to ' + @NewFilePath + ' by procedure ' + @procname
end

-- Destroying File System Object
EXEC @hr=sp_OADestroy @fso
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

IF @log > 1
    PRINT RTRIM(CAST(GETDATE() AS NVARCHAR(30))) + ' ' + @procname + ' procedure has finished';
Download md5: 60853e73c93a656f7f373809ce3f997b

2010/01/26

MSSQL 2005 procedure to write information to text file

CURRENT CONFIGURATION: MSSQL server 2005

OBJECTIVE: Write line to text, log file from MSSQL server in middle of backup operation to be able to confirm successful result from windows batch script or whatever.

SOLUTION:
I wrote SQL procedure. You can change destination database to whatever you want.
USE master
GO

-- set required options
EXEC sp_configure 'show advanced options',1
RECONFIGURE
GO
EXEC sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO

USE [sysman]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dba_write_to_file]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[dba_write_to_file]
GO

CREATE PROCEDURE [dbo].[dba_write_to_file]
    @file_name varchar(1000),
    @string varchar(1000),
    @send_email_proc  nvarchar(256),
    @log int = 2
AS
-- *****************************************************************************
-- Author:  Vadim Zenin http://vadimszenins.blogspot.com
-- Version:    1.00
-- Date:      10/12/2009 19:25:02
-- Procedure to write string to file
--
-- Usage:
-- In batch file: sqlcmd -E -dsysman -Q"EXEC sysman..dba_write_to_file 'C:\temp\testfile.txt', 'my test string', 'send_email', 1" >>%LOGFILE%
--
-- Parametrs:
-- @file_name example: 'C:\temp\testfile.txt'
-- @string example: 'my test string'
-- @send_email_proc example: 'send_email'
-- @log (0 - none, 1 - minimum, 2 - standard(default), 4 - debug) optinal
--
-- Tested platform:
-- MS SQL 2005
--
-- Version 1.00 revision:
--
--
-- This code is made available as is, without warranty of any kind. The entire
-- risk of the use or the results from the use of this code remains with the user.
-- *****************************************************************************
DECLARE
    @procname        nvarchar(256),
    @fso            int,
    @hr              int,
    @sqlcmd            nvarchar(600),
    @email_subj        nvarchar(255),
    @email_body        nvarchar(3000),
    @FileID         int

-- Get current stored procedure name
SELECT @procname = OBJECT_NAME(@@PROCID)
IF @log > 1
begin
    PRINT RTRIM(CAST(GETDATE() AS NVARCHAR(30))) + ' ' + @procname + ' procedure has started';
    PRINT N'The Database Engine instance ' + RTRIM(@@SERVERNAME) + N' is running SQL Server build '
    + RTRIM(CAST(SERVERPROPERTY(N'ProductVersion ') AS NVARCHAR(128)));
end
IF @log > 2
BEGIN
  PRINT 'Parametr 1: ' + @file_name;
  PRINT 'Parametr 2: ' + @string;
  PRINT 'Parametr 3: ' + @send_email_proc;
  PRINT 'Parametr 4: ' + RTRIM(@log);
END

-- Check requrements
If not exists (Select * from dbo.sysobjects where xtype='p' and name=@send_email_proc)
BEGIN
    SELECT @email_body = N'!? Stored procedure sysman..' + @send_email_proc + ' does not exist'
    IF @log >= 0
    PRINT @email_body
    RAISERROR (@email_body,16,1) with log
END

--------------------------------------------------------------------------------
-- Main procedure
--------------------------------------------------------------------------------

SET @hr = 0

-- Creating File System Object
EXEC @hr=sp_OACreate 'Scripting.FileSystemObject',@fso OUT
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error creating File System Object.' + @procname
  SELECT    @email_body = 'Error creating File System Object. Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      PRINT N' Sending failure email notification with subject: '
      PRINT @email_subj
    END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END

-- Opening a file
EXEC @hr = sp_OAMethod @fso, 'OpenTextFile', @FileID OUT,@file_name, 8, 1 -- Append if required (8)
--execute @hr = sp_OAMethod @fso, 'OpenTextFile', @FileID OUT,@file_name,  1
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error opening file.' + @procname
  SELECT    @email_body = 'Error opening file' + @file_name + ' . Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      PRINT N' Sending failure email notification with subject: '
      PRINT @email_subj
    END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END

-- Writing Text to File
EXEC @hr = sp_OAMethod @FileID, 'WriteLine', Null, @string
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error writing to file.' + @procname
  SELECT    @email_body = 'Error writing to file' + @file_name + ' . Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      PRINT N' Sending failure email notification with subject: '
      PRINT @email_subj
    END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END
else
begin
    IF @log > 0
      Print N'Writing to file ' + @file_name + ' by procedure ' + @procname
end

EXECUTE @hr = sp_OADestroy @FileID
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

-- Destroying File System Object
EXEC @hr=sp_OADestroy @fso
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

IF @log > 1
    PRINT RTRIM(CAST(GETDATE() AS NVARCHAR(30))) + ' ' + @procname + ' procedure has finished';
Download md5: 221c4765d32b91ae264e6e9d20c64d90