Friday, June 01, 2007

Get printer state using SNMP

Nothing easier on windows: there's a very useful library called OLEPRN.DLL sitting in system folder.

You may use VBS like follows:

dim o

' create an COM object to communicate to network printer

set o = createobject("oleprn.olesnmp")

' open a snmp session to printer using its IP address, public interface, retry count 1 and 6000 msecs as timeout

o.open "192.168.1.18","public",1,6000

' get printer state by state OID

x = o.GetAsByte("25.3.2.1.5.1") '

' output the state: 2 is OK, all others are warning/error codes '

' change MsgBox to desired notification method '

MsgBox x


 

You may want to write a C++ code:

#include
"stdafx.h"

#import
"d:\\windows\\system32\\oleprn.dll" no_namespace

#define USAGE _T("usage: %s <printer IP address>\nsample: %s 10.10.10.10")


 

int _tmain(int argc, _TCHAR* argv[])

{

    if(argc < 2)

    {

        wprintf(USAGE,argv[0],argv[0]);

        return -1;

    }

    CoInitialize(NULL);

    ISNMPPtr aPtr;

    _bstr_t bstrHost(argv[1]);

    _bstr_t bstrCommunity("public");

    _bstr_t bstrOID("25.3.2.1.5.1");

    HRESULT hr = S_OK;

    try

    {

        hr = aPtr.CreateInstance(__uuidof(SNMP));

        hr = aPtr->Open(bstrHost,bstrCommunity);

        int iStatus = aPtr->GetAsByte(bstrOID);

        printf("Status %d\n",iStatus);

        aPtr.Release();

    }

    catch(_com_error *e)

    {

        wprintf(e->ErrorMessage());

    }

    catch(...)

    {        

        wprintf(_T("Unknown error occured\n"));

    }

    CoUninitialize();

    return 0;

}


 

Or you may want to get it working in managed code:

http://blog.crowe.co.nz/archive/2005/08/08/182.aspx


 

Enjoy!