TelnetTarget.java 8.1 KB
package com.sitech.ismp.coll;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TelnetNotificationHandler;

/*******************************************************************************
 * This is a simple example of use of TelnetClient. An external option handler
 * (SimpleTelnetOptionHandler) is used. Initial configuration requested by
 * TelnetClient will be: WILL ECHO, WILL SUPPRESS-GA, DO SUPPRESS-GA. VT100
 * terminal type will be subnegotiated.
 * <p>
 * Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState() is
 * demonstrated. When connected, type AYT to send an AYT command to the server
 * and see the result. Type OPT to see a report of the state of the first 25
 * options.
 * <p>
 * 
 * @author Bruno D'Avanzo
 ******************************************************************************/
public class TelnetTarget implements TelnetNotificationHandler {
	static int totalchannel = 0;

	String CHARSET = "GBK";

	String OSHINT = ">";

	String user;

	String hostip;

	int hostport;

	String hostuser;

	String hostpass;

	public String channelNumber;

	public String lastOut = null;

	TelnetClient tc1 = null;

	InputStream is = null;

	OutputStream os = null;

	boolean INCONTAINER = false;

	synchronized static int incChannel() {
		totalchannel = (totalchannel + 1) % 1000000;
		return totalchannel;
	}

	public TelnetTarget() {
		incChannel();
		channelNumber = String.valueOf(totalchannel);
	}

	public void setCharSet(String charset) {
		this.CHARSET = charset;
	}

	/*
	 * public void setContext(PageContext pageContext) { this.pageContext =
	 * pageContext; out = pageContext.getOut(); INCONTAINER = true; }
	 */

	/***************************************************************************
	 * Callback method called when TelnetClient receives an option negotiation
	 * command.
	 * <p>
	 * 
	 * @param negotiation_code -
	 *            type of negotiation command received (RECEIVED_DO,
	 *            RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
	 *            <p>
	 * @param option_code -
	 *            code of the option negotiated
	 *            <p>
	 **************************************************************************/
	public void receivedNegotiation(int negotiation_code, int option_code) {
		String command = null;
		if (negotiation_code == TelnetNotificationHandler.RECEIVED_DO) {
			command = "DO";
		} else if (negotiation_code == TelnetNotificationHandler.RECEIVED_DONT) {
			command = "DONT";
		} else if (negotiation_code == TelnetNotificationHandler.RECEIVED_WILL) {
			command = "WILL";
		} else if (negotiation_code == TelnetNotificationHandler.RECEIVED_WONT) {
			command = "WONT";
		}
		System.out.println("Received " + command + " for option code "
				+ option_code);
	}

	public boolean loginWaitForString(InputStream is, long timeout, String[] out)
			throws Exception {
		return waitForString(is, ">", "$", timeout, out);
	}

	public boolean waitForString(InputStream is, String end, long timeout)
			throws Exception {
		String[] readbytes = new String[1];
		return waitForString(is, end, end, timeout, readbytes);
	}

	public boolean waitForString(InputStream is, String end, long timeout,
			String[] out) throws Exception {
		return waitForString(is, end, end, timeout, out);
	}

	/***************************************************************************
	 * Helper method. waits for a string with timeout
	 **************************************************************************/
	public boolean waitForString(InputStream is, String OSend1, String OSend2,
			long timeout, String[] out) throws Exception {
		byte buffer[] = new byte[1024];
		long starttime = System.currentTimeMillis();
		String readbytes = new String();
		String ss = new String();
		// System.out.println("OSEND1:" + OSend1);
		// System.out.println("OSEND2:" + OSend2);
		while ((readbytes.indexOf(OSend1) < 0)
				&& (readbytes.indexOf(OSend2) < 0)) {
			if ((timeout > 0)
					&& (System.currentTimeMillis() - starttime) > timeout) {
				break;
			} else {
				// System.out.println("Time Out!");
			}
			// if(is.available() > 0)
			// {
			int ret_read = is.read(buffer);
			if (ret_read > 0) {
				// if(is.available() > 0) System.out.print("#");
				ss = new String(buffer, 0, ret_read, CHARSET);
				readbytes = readbytes + ss;
				// System.out.print(ss);
			} else {
				Thread.sleep(100);
			}
		}
		lastOut = readbytes;
		out[0] = readbytes;
		int iPos = readbytes.indexOf(OSend1);
		if (iPos >= 0) {
			// System.out.println("1true" + "(" + OSend1 + ")" + iPos +
			// "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			return (true);
		} else {
			iPos = readbytes.indexOf(OSend2);
			if (iPos >= 0) {
				// System.out.println("2true" + "(" + OSend2 + ")" + iPos +
				// "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
				return (true);
			} else {
				// System.out.println("1false~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
				return (false);
			}
		}
	}

	public boolean init(String host, String user, String password)
			throws Exception {
		return login(host, 23, user, password);
	}

	public boolean login(String host, int port, String user, String password)
			throws Exception {
		this.hostip = host;
		this.hostport = port;
		this.hostuser = user;
		this.hostpass = password;

		tc1 = new TelnetClient();
		tc1.connect(host, port);
		is = tc1.getInputStream();
		os = tc1.getOutputStream();
		boolean cont = waitForString(is, "login:", 3000);

		if (cont) {
			os.write((user + "\n").getBytes());
			os.flush();
			cont = waitForString(is, "Password:", 1000);
		}
		if (cont) {
			os.write((password + "\n").getBytes());
			os.flush();
			String[] out = new String[1];
			cont = loginWaitForString(is, 3000, out);
			int crpos = out[0].lastIndexOf("\n");
			// OSHINT = out[0].substring(crpos+1,out[0].length()-1);
			// System.out.println("OSHINT:"+ OSHINT);
		}
		return cont;
	}

	public boolean logout() throws Exception {
		os.write("exit\n".getBytes());
		os.flush();
		tc1.disconnect();
		return true;
	}

	public boolean release() throws Exception {
		return logout();
	}

	public String[] exeShell(String command) throws Exception {
		return exeCommand(command, OSHINT, -1);
	}

	public String getCommandResult(String command) throws Exception {
		String[] result = exeCommand(command, OSHINT, -1);
		if (result[1].equals("ERR")) {
			return "";
		} else
			return result[0];
	}

	public String getResult(String server, String username, String password,
			String command) throws Exception {
		TelnetTarget telnettarget = new TelnetTarget();
		telnettarget.login(server, 23, username, password);
		String[] aa = telnettarget.exeShell(command);
		telnettarget.logout();
		/*
		 * for(int i=0;i<aa.length;i++){ System.out.println(i+"=:"+aa[i]); }
		 */
		if (!aa[1].equals("ERR")) {
			return aa[0];
		}
		return null;
	}

	/*
	 * out[1]=="ERR" 表示执行出错
	 */
	public String[] exeCommand(String command, String end, long timeout)
			throws Exception {
		boolean cont = true;
		String[] out = new String[3];
		out[1] = "ERR";
		if (cont) {
			os.write((command + "\n").getBytes());
			os.flush();
			cont = waitForString(is, end, timeout, out);

			int crPos = out[0].lastIndexOf("\n");
			out[1] = out[0].substring(crPos + 1, out[0].length() - 1);
			out[0] = out[0].substring(0, crPos);
			int crPos1 = out[0].indexOf("\n");
			if (crPos1 > -1) {
				out[2] = out[0].substring(0, crPos1);
				out[0] = out[0].substring(crPos1 + 1, out[0].length());
				/*
				 * if(out[2].equals(command)){
				 * out[0]=out[0].substring(crPos1+1,out[0].length()-1); }
				 */
			} else
				out[2] = "";

		}
		return out;
	}

	public static void main(String[] args) throws IOException, Exception {
		String server, username, password, command;
		server = "10.161.1.153";
		username = "iboss1";
		password = "otlke1";
		command = "/ibnms/ismp/bnms_agent/tuxedo/CM-00-04-001-01.sh";
		TelnetTarget webtl = new TelnetTarget();
		System.out
				.println(webtl.getResult(server, username, password, command));

		/*
		 * webtl.login(server,remoteport,username,password); String[] aa =
		 * webtl.exeShell(command); webtl.logout(); System.out.println(aa[0]);
		 */
	}
}