I am new on using the PYSNMP protocol, and I am trying to disconnect and connect ports from a switch through the SNMP protocol. I already have a switch communicating with the computer which in this case is going to be a raspberry pi 3, but I need a python script that do that for me. I have already managed to import the PYSNMP library, in to my scipt, what I know is that I have to use most probably the SET and a GET functions to change the states of the ports, from shutdonw to no shutdown, but I do not know how to do it or where can i start. Can you help me? What do you need to know so I can succeed, that i can tell you?
Do you know that your switch support SNMP-based port management? It really depends on the switch, also the way to flip ports is generally vendor-specific and should be described in switch documentation and/or MIB files.
My advice would be to first try SNMP with your switch like this:
$ snmpset -v2c -c <community> <hostname> IF-MIB::ifAdminStatus.interface.1 = up
or
$ snmpset -v2c -c <community> <hostname> IF-MIB::ifAdminStatus.interface.1 = down
Where 1
is port #0 index. Write SNMP community string may be set to private
by default.
Although your switch may use some other MIB object for port management or do not support SNMP at all.
Once you figure out how to use SNMP for your purpose, you could express that in pysnmp like this.
EDIT:
from pysnmp.hlapi import *
setcommunity = 'private'
host = 'demo.pysnmp.com'
port = 1
snmp_engine = SnmpEngine()
set_gen = setCmd(snmp_engine,
CommunityData(setcommunity),
UdpTransportTarget((host, 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-SMI', 'mib-2', '105.1.1.1.3.1.%d' % port), Integer(2)))
errorIndication, errorStatus, errorIndex, varBinds = next(set_gen)
if errorIndication or errorStatus:
print('SNMP error: %s' % errorIndication or errorStatus)
else:
print('SNMP succeeded')
Keep in mind that you can flip many (dozens) ports via a single SNMP command.