⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snmptftpservlet.java

📁 实现cisco snmp tftp,能用snmp tftp上传下载文件
💻 JAVA
字号:
/* zhang ji wang 	2003.12.20*/import java.util.* ;import java.lang.* ;import java.io.* ;import javax.servlet.* ;import javax.servlet.http.* ;import java.net.*;import java.text.*;import org.opennms.protocols.snmp.*;public class SnmpTftpServlet extends HttpServlet{	private static String FailureCause;		public SnmpTftpServlet()	{			}			public void init( ServletConfig config ) throws ServletException	{		super.init( config ) ;	}		public void destroy() 	{			}		public void doGet( HttpServletRequest request , HttpServletResponse response )		throws IOException , ServletException	{		//	}		public void doPost( HttpServletRequest request , HttpServletResponse response )		throws IOException , ServletException	{		//	}			public void service( HttpServletRequest request , HttpServletResponse response )		throws IOException , ServletException	{		synchronized(this) 		{			response.setContentType("text/html;charset=gb2312");			//ServletOutputStream out = response.getOutputStream();			System.err.println("request start");									String FileName = request.getParameter( "FileName" );				String FileType = request.getParameter( "FileType" );			String RemoteAddr = request.getParameter( "RemoteAddr" );			String Community =  request.getParameter( "Community" );			String Flag = request.getParameter( "UpOrDown" );					if(snmpRequest(RemoteAddr, Community, FileName, FileType, Flag))			{				response.addIntHeader("Result", 1);				//response.addHeader("FileName", FileName); 				//out.println(FileName);			}				else			{				response.addIntHeader("Result", 0);				response.addHeader("FailureCause", FailureCause);				//out.println(FailureCause);			}		}			}		boolean snmpRequest(String RemoteAddr, String Community, String FileName, String FileType, String Flag)	{		int ft;		snmptftp walker = new snmptftp();				walker.setCommunity(RemoteAddr, Community);				if( FileType.equals("startupConfig"))			ft = 3;		else if(FileType.equals("runningConfig"))			ft = 4;		else if(FileType.equals("iosFile"))			ft = 2;		else		{			FailureCause = "参数(文件类型)错误";			return false;		}			walker.setVarValue(FileName, Flag.equals("T"), ft);				InetAddress remote = null;				try		{			remote = InetAddress.getByName(walker.m_host);		}		catch(UnknownHostException e)		{			System.err.println("UnknownHostException: " + e.getMessage());			FailureCause = "参数(路由器地址)错误";			return false;		}				SnmpPeer peer = new SnmpPeer(remote);		if(walker.m_port != -1)			peer.setPort(walker.m_port);				if(walker.m_timeout != -1)			peer.setTimeout(walker.m_timeout);				if(walker.m_retries != -1)			peer.setRetries(walker.m_retries);		SnmpParameters parms = peer.getParameters();		parms.setVersion(SnmpSMI.SNMPV2);				if(walker.m_community != null)		{			parms.setWriteCommunity(walker.m_community);			parms.setReadCommunity(walker.m_community);		}			//		// Now create the session, set the initial request		// and walk the tree!		//		SnmpSession session = null;		try		{			session = new SnmpSession(peer);		}		catch(SocketException e)		{			System.err.println("SocketException creating the SNMP session");			System.err.println("SocketException: " + e.getMessage());			FailureCause = "SNMP请求失败,建立连接错误";			return false;		}				session.setDefaultHandler(walker);				SnmpPduRequest pdu = new SnmpPduRequest(SnmpPduPacket.SET);		pdu.addVarBindAt(0, walker.m_mibvar[walker.start_ndx]);		pdu.setRequestId(SnmpPduPacket.nextSequence());				try		{			synchronized(session)			{				session.send(pdu);				session.wait();			}		}		catch(InterruptedException e) 		{ 			// do nothing		}		finally		{			session.close();		}		FailureCause = walker.getFailureCause();		return walker.getResult();	}}class snmptftp extends Object implements SnmpHandler{	String		m_community  	= null;			// -c	int		m_retries 	= 2;			// -r		int		m_timeout	= 5000;			// -t	int		m_port		= 161;			// -p	String		m_host		= "172.16.1.3";		private static String[] IosfileFailure = {"copyInvalidOperation", "copyInvalidProtocol",						  "copyInvalidSourceName", "copyInvalidDestName", 						  "copyInvalidServerAddress", "copyDeviceBusy",						  "copyDeviceOpenError", "copyDeviceError",						  "copyDeviceNotProgrammable", "copyDeviceFull",						  "copyFileOpenError", "copyFileTransferError",						  "copyFileChecksumError", "copyNoMemory",						  "copyUnknownFailure"};						 	private static String[] ConfigFailure = {"unknown", "badFileName", "timeout", "noMem", "noConfig"};					private boolean	m_result = false;	private String   failure_cause;				public static SnmpVarBind[]  m_mibvar = null;	private int ndx = 0;	public int start_ndx ;		static	{		m_mibvar = new SnmpVarBind[17];				m_mibvar[0] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.2.777");		m_mibvar[1] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.3.777");		m_mibvar[2] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.4.777");		m_mibvar[3] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.5.777");		m_mibvar[4] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.6.777");		m_mibvar[5] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.14.777");		m_mibvar[6] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.10.777");		m_mibvar[7] = new SnmpVarBind(".1.3.6.1.4.1.9.9.96.1.1.1.1.13.777");		m_mibvar[8] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.2.777");		m_mibvar[9] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.3.777");		m_mibvar[10] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.4.777");		m_mibvar[11] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.5.777");		m_mibvar[12] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.6.777");		m_mibvar[13] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.11.777");		m_mibvar[14] = new SnmpVarBind(".1.3.6.1.4.1.9.9.10.1.2.1.1.8.777");	}				/**	 * Defined by the SnmpHandler interface. Used to process internal session	 * errors.	 *	 * @param session	The SNMP session in error.	 * @param err		The Error condition	 * @param pdu		The pdu associated with this error condition	 *	 */	public void snmpInternalError(SnmpSession session, int err, SnmpSyntax pdu)	{		System.err.println("An unexpected error occured with the SNMP Session");		System.err.println("The error code is " + err);		failure_cause = "SNMP请求失败,程序内部错误";		synchronized(session)		{			session.notify();		}	}		/**	 * This method is define by the SnmpHandler interface and invoked	 * if an agent fails to respond.	 *	 * @param session	The SNMP session in error.	 * @param pdu		The PDU that timedout.	 *	 */	public void snmpTimeoutError(SnmpSession session, SnmpSyntax pdu)	{		System.err.println("The session timed out trying to communicate with the remote host");		m_result = false;		failure_cause = "SNMP请求失败,可能路由器地址或者Community不存在";		synchronized(session)		{			session.notify();		}	}		/**	 * This method is defined by the SnmpHandler interface and invoked	 * when the agent responds to the management application.	 *	 * @param session	The session receiving the pdu.	 * @param cmd		The command from the pdu. 	 * @param pdu		The received pdu.	 *	 * @see org.opennms.protocols.snmp.SnmpPduPacket#getCommand	 */ 	public void snmpReceivedPdu(SnmpSession session, int cmd, SnmpPduPacket pdu)	{		SnmpPduRequest req = null;		if(pdu instanceof SnmpPduRequest)		{			req = (SnmpPduRequest)pdu;		}				if(pdu.getCommand() != SnmpPduPacket.RESPONSE)		{			System.err.println("Error: Received non-response command " + pdu.getCommand());			failure_cause = "SNMP请求失败,程序内部错误";			synchronized(session)			{				session.notify();			}			return;		}				if(req.getErrorStatus() != 0)		{			System.out.println("End of mib reached");			/*synchronized(session)			{				session.notify();			}			return;*/			failure_cause = "SNMP请求失败,无法获得MIB值";			ndx = 20;					}				//		// Passed the checks so lets get the first varbind and		// print out it's value		//		SnmpVarBind vb = pdu.getVarBindAt(0);				System.out.println(vb.getName().toString() + ": " + vb.getValue().toString());		if(vb.getValue().typeId() == SnmpEndOfMibView.ASNTYPE )		{			System.out.println("End of mib reached");			/*synchronized(session)			{				session.notify();			}			return;*/			failure_cause = "SNMP请求失败,无法获得MIB值";			ndx = 20;		}						if( ndx - start_ndx < 5)		{			SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.SET);			ndx++;			newReq.addVarBindAt(0, m_mibvar[ndx]);			newReq.setRequestId(SnmpPduPacket.nextSequence());			session.send(newReq);		}		else if( ndx - start_ndx == 5)		{			SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.GET);			ndx++;			newReq.addVarBindAt(0, m_mibvar[ndx]);			newReq.setRequestId(SnmpPduPacket.nextSequence());			session.send(newReq);									}		else if( ndx - start_ndx == 6 )		{			SnmpInt32 int32 = (SnmpInt32)vb.getValue();			int mibvar = int32.getValue();						if( (start_ndx == 0 && mibvar == 2) || (start_ndx == 8 && mibvar == 1))			{				try				{					Thread.sleep(1000);				}				catch( InterruptedException e)				{								}				SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.GET);				newReq.addVarBindAt(0, m_mibvar[ndx]);				newReq.setRequestId(SnmpPduPacket.nextSequence());				session.send(newReq);			}			else if( start_ndx == 0 && mibvar != 2)			{				if(mibvar == 3)				{					m_result = true;					SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.SET);					m_mibvar[5].setValue(new SnmpInt32(6));					newReq.addVarBindAt(0, m_mibvar[5]);					newReq.setRequestId(SnmpPduPacket.nextSequence());					session.send(newReq);					ndx = 20;				}				else if(mibvar == 4)				{					ndx++;					SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.GET);					newReq.addVarBindAt(0, m_mibvar[ndx]);					newReq.setRequestId(SnmpPduPacket.nextSequence());					session.send(newReq);				}				}			else if( start_ndx == 8 && mibvar != 1)			{				if(mibvar == 2)				{					m_result = true;				}				else 				{					failure_cause = "TFTP传输失败(" + IosfileFailure[mibvar-3] + ")";				}				SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.SET);				m_mibvar[13].setValue(new SnmpInt32(6));				newReq.addVarBindAt(0, m_mibvar[13]);				newReq.setRequestId(SnmpPduPacket.nextSequence());				session.send(newReq);				ndx = 20;				}		}		else if( ndx == 7)		{			SnmpInt32 int32 = (SnmpInt32)vb.getValue();			int mibvar = int32.getValue();						failure_cause = "TFTP传输失败(" + ConfigFailure[mibvar-1] + ")";						SnmpPduRequest newReq = new SnmpPduRequest(SnmpPduPacket.SET);			m_mibvar[5].setValue(new SnmpInt32(6));			newReq.addVarBindAt(0, m_mibvar[5]);			newReq.setRequestId(SnmpPduPacket.nextSequence());			session.send(newReq);			ndx = 20;		}		else		{			synchronized(session)			{				session.notify();			}				}	}		public void setCommunity(String host, String community)	{			m_host = host;		m_community = community;	}		public void setVarValue(String filename, boolean isdownload, int filetype)	{		InetAddress tftpserver = null;		try		{			tftpserver = InetAddress.getByName("202.103.106.10");		}		catch(UnknownHostException e)		{			System.err.println("UnknownHostException: " + e.getMessage());		}				if( filetype == 2)		{			StringTokenizer sto = new StringTokenizer(filename, "_");			String destfile = null;			start_ndx = 8;			ndx = 8;			int i = 0;			while(sto.hasMoreTokens() && i < 2)			{				destfile = sto.nextToken();				i++;			}			if( isdownload )			{				m_mibvar[8].setValue(new SnmpInt32(3));				m_mibvar[9].setValue(new SnmpInt32(1));				m_mibvar[10].setValue(new SnmpIPAddress(tftpserver.getAddress()));				m_mibvar[11].setValue(new SnmpOctetString(destfile.getBytes()));				m_mibvar[12].setValue(new SnmpOctetString(filename.getBytes()));				m_mibvar[13].setValue(new SnmpInt32(1));			}			else			{				m_mibvar[8].setValue(new SnmpInt32(1));				m_mibvar[9].setValue(new SnmpInt32(1));				m_mibvar[10].setValue(new SnmpIPAddress(tftpserver.getAddress()));				m_mibvar[11].setValue(new SnmpOctetString(filename.getBytes()));				m_mibvar[12].setValue(new SnmpOctetString(destfile.getBytes()));				m_mibvar[13].setValue(new SnmpInt32(1));			}		}		else		{			ndx = 0;			start_ndx = 0;			m_mibvar[0].setValue(new SnmpInt32(1));			if( isdownload )			{				m_mibvar[1].setValue(new SnmpInt32(filetype));				m_mibvar[2].setValue(new SnmpInt32(1));			}			else			{				m_mibvar[1].setValue(new SnmpInt32(1));				m_mibvar[2].setValue(new SnmpInt32(filetype));			}			m_mibvar[3].setValue(new SnmpIPAddress(tftpserver.getAddress()));			m_mibvar[4].setValue(new SnmpOctetString(filename.getBytes()));			m_mibvar[5].setValue(new SnmpInt32(1));		}	}		public boolean getResult()	{		return m_result;	}		public String getFailureCause()	{		return failure_cause;	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -