from pysnmp.hlapi import *
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# SNMP query function
def snmp_query(ip, community, oid):
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData(community),
UdpTransportTarget((ip, 161)),
ContextData(),
ObjectType(ObjectIdentity(oid)))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print(‘%s at %s’ % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) – 1][0] or ‘?’))
else:
for varBind in varBinds:
return varBind[1].prettyPrint()
# Google Sheets API setup
scope = [“https://spreadsheets.google.com/feeds”,’https://www.googleapis.com/auth/spreadsheets’,”https://www.googleapis.com/auth/drive.file”,”https://www.googleapis.com/auth/drive”]
creds = ServiceAccountCredentials.from_json_keyfile_name(“credentials.json”, scope)
client = gspread.authorize(creds)
# Open the Google Sheet by title
sheet = client.open(“my_sheet”).sheet1
# SNMP query and insert data into Google Sheet
ip = “192.168.1.1”
community = “public”
oid = “1.3.6.1.2.1.1.1.0” # example OID for system description
data = snmp_query(ip, community, oid)
sheet.append_row([data])
print(“Data inserted into Google Sheet.”)