#!/usr/bin/python

###############################################
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
###############################################
# CHECK SNMP IFACE
# Version 0.1   Date 09/12/2004
###############################################
import os,sys,optik,re

global iface_status

def parse_cli():
	parser=optik.OptionParser()

	parser.add_option("-H",help="Host Target",action="store",type="string",dest="host",default="none")
	parser.add_option("-i",help="Interface",action="store",type="string",dest="iface",default="none")
	parser.add_option("-C",help="Community",action="store",type="string",dest="community",default="public")
	parser.add_option("-v",help="SNMP Version (1|2c)",action="store",type="string",dest="version",default="2c")

	(options, args) = parser.parse_args()
	
	if options.host!="none" and options.iface!="none":
		return options
	else:
		print "Missing Required Arguments ... \n\n"
		parser.print_help()
	
def get_iface_mib(host,iface,community,version):
	#return the number identifier of iface
	try:
		tmp_iface=os.popen("/usr/bin/snmpwalk -c "+community+" -v "+version+" "+host+" ifDescr |grep "+iface)
		tmp_re=re.compile("ifDescr\.\d+")
		tmp_iface_id=tmp_re.search(tmp_iface.read()).group().split(".")

		return tmp_iface_id[1] #Interface SNMP ID.
	except:
		print "Impossible to Retrieve SNMP info for interface "+iface
		sys.exit(3)

def get_iface_status(host,iface_id,community,version):
	tmp_iface_status=os.popen("/usr/bin/snmpget -c "+community+" -v "+version+" "+host+" ifOperStatus."+iface_id)
	tmp_status=tmp_iface_status.read()
	if re.compile("up").search(tmp_status):
		iface_status="UP"
	elif re.compile("down").search(tmp_status):
		iface_status="DOWN"
	else:
		iface_status="UNKNOWN"
	
	return iface_status
	
def main():
	options=parse_cli()	
	id=get_iface_mib(options.host,options.iface,options.community,options.version)

	status=get_iface_status(options.host,id,options.community,options.version)

	#Evaluate status

	if status=="UP":
		print "Interface "+options.iface+" appears to be UP"
		sys.exit(0)
	elif status=="DOWN":
		print "Interface "+options.iface+" appears to be DOWN!!!"
		sys.exit(2)
	else:
		print "Interface "+options.iface+" state is UNKNOWN"
		sys.exit(3)
	


main()
