TelnetThread.java 7.09 KB
package com.sitech.util.upload;

import org.apache.commons.net.telnet.TelnetClient;
import org.apache.log4j.Logger;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Vector;

public class TelnetThread implements RomoteController {
	private Logger logger = Logger.getLogger(TelnetThread.class);

	// 是否认证完毕
	private boolean autorized = false;
	private String ip = null;
	private int port = 23;
	private String username = null;
	private String password = null;
	private String specPrompt = null;

	// 存放命令执行结果
	private StringBuffer result = new StringBuffer();

	private TelnetClient telnet = new TelnetClient();
	private InputStream is;
	private PrintStream os;

	public TelnetThread(String ip, int port, String username, String password) {
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
	}
	
	public TelnetThread(String ip, int port, String username, String password, String specPrompt) {
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
		this.specPrompt = specPrompt;
	}

	public void initial() {
		try {
			telnet.connect(this.ip, this.port);

			is = telnet.getInputStream();
			os = new PrintStream(telnet.getOutputStream());
		} catch (Exception e) {
			logger.error("创建telnet连接失败.", e);
			return;
		}

		if (!telnet.isConnected()) {
			return;
		}

		read("login: ");
		doCommand(username);
		read("Password: ");
		doCommand(password);
		getResult();
		
		
	}

	public String read(String pattern) {
		try {
			char lastChar = pattern.charAt(pattern.length() - 1);
			StringBuffer sb = new StringBuffer();

			char ch = (char) is.read();
			while (true) {
				sb.append(ch);
				if (ch == lastChar) {
					if (sb.toString().endsWith(pattern)) {
						logger.info(sb.toString());
						return sb.toString();
					}
				}
				ch = (char) is.read();
			}
			
		} catch (Exception e) {
			logger.error("Exception while read " + pattern, e);
		}
		return null;
	}
	
	public String getResultAsStr(String cmd) {
		doCommand(cmd);

		return getResult();
	}

	public Vector<String> getResultAsVector(String command) {
		Vector<String> vResult = new Vector<String>();
		try{
			this.doCommand(command);
			String strResult = this.getResult();

			if (strResult != null) {
				String[] results = strResult.split("\n");	
				for(String line : results){
					if(line.indexOf("have mail in") >=0 ){
						continue;
					}
					
					vResult.add(line);
				}
			}
		}catch (Exception e) {
			logger.error("Exception while do command:" + command, e);
		}
		
		String logInfo = "-- do command: " + command +"\n";
		for(String line : vResult){
			logInfo += line + "\n";
		}
		logger.info(logInfo);
		
		return vResult;
	}

	public String getResult() {
		
		try {
			char ch = (char) is.read();

			do {
				result.append(ch);
				
				if (specPrompt != null && !specPrompt.trim().equals("")) {
					if (result.toString().endsWith(specPrompt)) {
						break;
					}
				} else if (((!result.toString().endsWith("HELP <command>")) && result.toString().endsWith(">"))
						|| result.toString().endsWith("$")) {
					break;
				}

				ch = (char) is.read();
			} while (true);
			autorized = true;
		} catch (Exception e) {
			autorized = false;
			logger.error("Exception while getResult.", e);
			return null;
		}

		String rs = result.toString();
		
		int endIdx = rs.lastIndexOf("\n");
		if(endIdx > 0){
			rs = rs.substring(0, endIdx);
		}
		
		return rs;
	}

	public boolean isRunning(String keywords, String username) {
		String command = "ps -ef | grep " + keywords;
		if (username != null && !"".equals(username)) {
			command += " | grep " + username;
		}
		command = command + " | grep -v grep";
		doCommand(command);
		String result = this.getResult();
		if (result != null && result.indexOf(keywords) != -1) {
			return true;
		} else {
			return false;
		}

	}

	public boolean isRunning(String keywords) {
		doCommand("ps -ef | grep " + keywords);
		String result = this.getResult();
		result = result.replaceAll("grep " + keywords, " ");
		if (result != null && result.indexOf(keywords) != -1) {
			return true;
		} else {
			return false;
		}
	}

	public void doCommand(String command) {
		try {
			os.println(command);
			os.flush();

			result = new StringBuffer();
		} catch (Exception e) {
			logger.error("Exception while doCommand " + command, e);
		}
	}

	public void receivedNegotiation(int negotiation_code, int option_code) {
	}

	public void close() {
		try {
			byte b = 0x03;
			os.write(b);
			os.flush();
			this.doCommand("exit");
			if (telnet != null && telnet.isConnected()) {
				telnet.disconnect();
			}
			telnet = null;
		} catch (Exception e) {
			logger.error("Exception while close connnection.", e);
		}
	}

	public boolean isAuthorized() {
		return this.autorized;
	}

	public boolean isExistDir(String dir) {
		boolean success = true;
		this.doCommand("cd " + dir);

		if (this.getResult().indexOf(dir + ":  not found") != -1) {
			success = false;
		}
		return success;
	}

	public int childCountOfDir(String dir) {
		int count = 0;
		try {
			if (this.isExistDir(dir)) {
				doCommand("cd " + dir + ";ls -l | wc -l");
				String s = null;
				s = getResult();
				String[] s1 = s.split("\n");
				if (s1 != null) {
					count = new Integer(s1[1].trim()).intValue() - 1;
				}
			} else {
				return -1;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
		return count;
	}

	public boolean createDir(String dir) {
		boolean isExist = false;
		if (dir != null && !dir.trim().equals("") && this.isExistDir(dir)) {
			isExist = true;
		}
		// 逐层分析目录,如果没有则创建.
		if (dir != null && !dir.trim().equals("") && !this.isExistDir(dir)) {
			String[] split_dir = dir.split("/");
			for (int i = 0; i < split_dir.length; i++) {
				String path = "";
				for (int j = 0; j <= i; j++) {
					if (split_dir[j] != null && !split_dir[j].equals("")) {
						path += "/" + split_dir[j];
					}
				}
				if (path != null && !path.equals("")) {
					if (!this.isExistDir(path)) {
						this.doCommand("mkdir " + path);
						this.getResult();
					}
					if (!this.isExistDir(path)) {
						return false;
					}
				}
			}
			if (this.isExistDir(dir)) {
				isExist = true;
			}
		}
		return isExist;
	}

	public boolean isUsed(int port) {
		this
				.doCommand("netstat -an | grep -v TIME_WAIT | awk '{print $4}' | grep "
						+ port + "");
		String result = this.getResult();
		if (result != null && result.indexOf("" + port) >= 0) {
			return true;
		}

		return false;
	}

	public String getIpAddr() {
		return this.ip;
	}

	public String executeCommand(String command) throws Exception
    {
		return "";
    }
	public String executeCommand(List<String> commandList) throws Exception
	{
		 return "";
	}
	public RomoteController cloneObject()
    {
		return null;
    }
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			TelnetThread tt = new TelnetThread("172.21.1.71", 23, "yfbnms",
					"yfbnms");
			tt.initial();
			tt.doCommand("prtconf |grep 'Number Of Processors:'");

			System.out.println(tt.getResult());
			tt.close();

		}
		
	}
	
	public String getError(){
		return "";
	}
}