Shell for Telnet

package com.wz.test;

import java.io.InputStream;
import java.io.PrintStream;
import org.apache.commons.net.telnet.TelnetClient;

public class Shell {
	private TelnetClient telnet;
	private InputStream in;
	private PrintStream out;
	private char prompt = '$';
	private String pwdString;

	public Shell(String ip, int port, String user, String password, int timeout) throws Exception {
		telnet = new TelnetClient();
		telnet.setConnectTimeout(timeout);
		telnet.connect(ip, port);
		in = telnet.getInputStream();
		out = new PrintStream(telnet.getOutputStream());
		this.prompt = user.equals("root") ? '#' : '$';
		this.pwdString = "Password";
		login(user, password);
	}
	/**
	 * 登录
	 * @Title login
	 * @author Administrator
	 * @param user
	 * @param password
	 * @return void
	 */
	public void login(String user, String password) {
		readUntil("login:");
		write(user);
		readUntil(pwdString+":");
		write(password);
		readUntil(prompt + "");
	}
	/**
	 * 读取分析结果
	 * @Title readUntil
	 * @author Administrator
	 * @param pattern
	 * @return
	 * @return String
	 */
	public String readUntil(String pattern) {
		try {
			StringBuffer sb = new StringBuffer();
			char lastChar = pattern.charAt(pattern.length() - 1);
			char ch = (char) in.read();
			while (ch != -1) {
				sb.append(ch);
				if (ch == lastChar && sb.toString().endsWith(pattern)) {
					return sb.toString();
				}
				ch = (char) in.read();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 写操作
	 * @Title write
	 * @author Administrator
	 * @param value
	 */
	public void write(String value) {
		try {
			out.println(value);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 向目标发送命令
	 * @Title sendCommand
	 * @author Administrator
	 * @param command
	 * @return
	 * @return String
	 */
	public String sendCommand(String command) {
		try {
			write(command);
			return readUntil(prompt + "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 关闭连接
	 * @Title  disConnect 
	 * @author  Administrator
	 * @return  void
	 */
	public void disConnect() {
		try {
			if(telnet != null) {
            	telnet.disconnect();  
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		System.out.println("启动Telnet...");
		String ip = "192.168.1.242";
		int port = 23;
		String user = "root";
		String password = "123456";
		int timeout = 5000;
		try {
			Shell telnet = new Shell(ip, port, user, password,timeout);
			//System.out.println(telnet.sendCommand("mysqldump -uroot -p123456 --verbose --databases erp > /home/wangzi/tmp/qq.sql"));
			String rs = telnet.sendCommand("ifconfig");
			System.out.println(new String(rs.getBytes("ISO-8859-1"),"GBK"));
			telnet.disConnect();
		} catch (Exception e) {
			System.out.println("连接失败,请确认ip地址、端口号、用户名、密码是否正确,同时确认目标主机是否开启Telnet...");
		}
	}
}



commons-net

你可能感兴趣的:(Java,SE)