Search code examples
arraysbatch-filesnmpoid

Get Toner Level from printers via SNMP Batch


I was asked to write a program that asks all printers in the network about there Name, Location and CMYK Toners (How many percentages are left). So i started with the OID's and tried it for only one printer. This worked. Then i wrote a .bat file with all querys i had to do. I made an array for all 97 printers. As i would use the array in the Codeline nothing worked. In my opinion the Codeline doesn't accept the array. I googled for everything and tried everything but nothing worked so I wanted to ask you what my problem is. Also I want to write it out in an .txt file.

My Code:

@echo off

setlocal enableDelayedExpansion 

SET count=0

SET a[0]= 172.22.10.3
SET a[1]= 172.22.10.2
SET a[2]= 172.22.10.1
SET a[3]= 172.22.10.5

snmpwalk -v2c -c public %a[%count%]% 5 1.3.6.1.2.1.25.3.2.1.3.1
>>C:\Temp\Drucker.txt
//Printer Name

snmpwalk -v2c -c public %a[%count%]% 1.3.6.1.2.1.1.6 >>C:\Temp\Drucker.txt
//Printer Location

snmpwalk -v2c -c public %a[%count%]% 1.3.6.1.2.1.43.11.1.1.9.1.4
>>C:\Temp\Drucker.txt
//Black Toner   

snmpwalk -v2c -c public %a[%count%]% 1.3.6.1.2.1.43.11.1.1.9.1.1
>>C:\Temp\Drucker.txt
//Cyan Toner

snmpwalk -v2c -c public %a[%count%]% 1.3.6.1.2.1.43.11.1.1.9.1.2
>>C:\Temp\Drucker.txt
//Magenta Toner

snmpwalk -v2c -c public %a[%count%]% 1.3.6.1.2.1.43.11.1.1.9.1.3
>>C:\Temp\Drucker.txt
//Yellow Toner

endlocal

The Picture is showing the error message that comes when I start the .bat file.

enter image description here


Solution

  • Here is the way you should iterate over an array:

    @echo off 
    setlocal enabledelayedexpansion 
    
    set hosts[0]=172.22.10.3
    set hosts[1]=172.22.10.2
    set hosts[2]=172.22.10.1
    set hosts[3]=172.22.10.5
    
    for /l %%n in (0,1,3) do ( 
       echo !hosts[%%n]! 
    )
    

    The output looks like:

    172.22.10.3
    172.22.10.2
    172.22.10.1
    172.22.10.5
    

    UPDATE: So you just put your snmpwalk calls into the loop like this:

    for /l %%n in (0,1,3) do ( 
        echo Getting data from host: !hosts[%%n]! 
    
        echo Printer Name
        snmpwalk -v2c -c public !hosts[%%n]! 1.3.6.1.2.1.1.5
        echo Printer Location
        snmpwalk -v2c -c public !hosts[%%n]! 1.3.6.1.2.1.1.6 
        echo Black Toner   
        snmpwalk -v2c -c public !hosts[%%n]! 1.3.6.1.2.1.43.11.1.1.9.1.4 
        echo Cyan Toner      
        snmpwalk -v2c -c public !hosts[%%n]! 1.3.6.1.2.1.43.11.1.1.9.1.1
        echo Magenta Toner
        snmpwalk -v2c -c public !hosts[%%n]! 1.3.6.1.2.1.43.11.1.1.9.1.2
        echo Yellow Toner
        snmpwalk -v2c -c public !hosts[%%n]! 1.3.6.1.2.1.43.11.1.1.9.1.3
    )
    

    IMPORTANT: Consider using -Oqv option of snmpwalk to print values only.