I use multiprocessing in my python code.
My python code imports Pysnmp and multiprocessing.
Half of the time my code runs smoothly.
But unfortunately half of the other time my code doesn't work and shows the exception "pyasn1.error.pyasn1 error: type tagset".
My code first creates a "multiprocessing.dummy.Pool(numOfThreads)" with a number of threads.
Then it calls "p.map(sendSNMPGet, [ipRange + '.' + str(x) for x in range(1,256)])" which takes the function "sendSNMPGet" as the thread function, and calls the function 255 times with the values of "1-255".
This is my code:
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto.rfc1902 import Integer, IpAddress, OctetString
import multiprocessing.dummy
import multiprocessing
def SNMPGet(ip, community, oid, version = 1):
generator = cmdgen.CommandGenerator()
comm_data = cmdgen.CommunityData('server', community, version) # 1 means version SNMP v2c
transport = cmdgen.UdpTransportTarget((ip, 161),timeout=0.5,retries=2)
real_fun = getattr(generator, 'getCmd')
res = (errorIndication, errorStatus, errorIndex, varBinds)\
= real_fun(comm_data, transport, oid)
if (errorStatus == 2): #Is there an EndOfMib() Error
return
elif (errorIndication is None or errorStatus is True):
with open("Maprinter.txt", "a") as myfile: myfile.write("Date is: " + datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " IP is: " + ip + ", Response: %s\n" % varBinds)
print("IP is: " + ip + ", Response: %s\n" % varBinds)
return
def sendSNMPGet(ip):
return SNMPGet(ip, 'public', '1.3.6.1.2.1.43.5.1.1.1.1', 1)
def snmp_range(ipRange, start, end):
num_threads = 4 * multiprocessing.cpu_count()
p = multiprocessing.dummy.Pool(num_threads)
p.map(sendSNMPGet, [ipRange + '.' + str(x) for x in range(start,end)])
def GetIpsRange(ips):
print('starting scan')
if __name__ == "__main__":
if(ips != ''): #if there are ips in registry
for ip in range(len(ips)):
snmp_range(ips[ip], 1, 256)
print('ending scan')
GetIpsRange('10.0.0')
Despite the use of Pysnmp I think my exception occurs due to lack of proper coding of multiprocessing. How could I change my code to handle this exception or even better, prevent it from happening?