Shell for Telnet

3105 단어 JavaSE
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

좋은 웹페이지 즐겨찾기