SSHThread.java 8.59 KB
package com.sitech.util.upload;

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

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHThread extends Thread implements RomoteController {
	private Logger logger = Logger.getLogger(SSHThread.class);

	private String host;
	private int port;
	private String user;
	private String password;
	private boolean autorized = false;
	private String keywords = null;
	// 存放命令执行结果
	private StringBuffer result = new StringBuffer();

	private Session session;
	private Channel channel;

	private String error;

	public SSHThread(String host, int port, String user, String password) {
		this.host = host;
		this.port = port;
		this.user = user;
		this.password = password;
	}
	
	/**
	 * 初始化SSH连接
	 */
	public void initial() {
		JSch jsch = new JSch();
		try {
			session = jsch.getSession(user, host, port);
			session.setPassword(this.password);

			session.setConfig("StrictHostKeyChecking", "no");

			// 超时时间
			session.connect(30000);
			this.autorized = true;
		} catch (Exception e) {
			error = e.getMessage();
			this.autorized = false;
			logger.error("Create ssh session Failed!! " + "ip=" + this.host
					+ ", username=" + this.user, e);
		}
	}

	public void run() {
		super.run();
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		try {
			if (channel != null && channel.isConnected()) {
				try {
					channel.disconnect();
				} catch (Exception e) {
					logger.error("Exception while close ssh channel", e);
				}
			}

			if (session != null && session.isConnected()) {
				try {
					session.disconnect();
				} catch (Exception e) {
					logger.error("Exception while close ssh session", e);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 执行命令
	 */
	public void doCommand(String command) {
		if (!this.isAuthorized()) {
			return;
		}

		try {
			this.result = new StringBuffer();
			channel = session.openChannel("exec");
			if (command != null && !command.endsWith("\n")) {
				command = command + "\n";
			}
			((ChannelExec) channel).setCommand(command);
			channel.connect();
		} catch (JSchException e1) {
			this.autorized = false;
			logger.error("SSH session is down!! " + "ip=" + this.host
					+ ", username=" + this.user, e1);
		} catch (Exception e) {
			logger.error("Exception while do command:" + command, e);
		}
	}

	public String getResult() {
		InputStream is = null;
		InputStream extIs = null;

		byte[] tmp = new byte[1024];
		long timeout = 30000;
		long wait = 0;

		try {
			if (!this.isAuthorized()) {
				return "";
			}

			is = channel.getInputStream();
			extIs = channel.getExtInputStream();

			while (is != null && timeout > wait) {
				while (is.available() > 0) {
					int i = is.read(tmp, 0, 1024);
					if (i <= 0)
						break;
					this.result.append(new String(tmp, 0, i));
				}

				while (extIs.available() > 0) {
					int i = extIs.read(tmp, 0, 1024);
					if (i <= 0)
						break;
					this.result.append(new String(tmp, 0, i));
				}

				if (channel.isClosed() || channel.isEOF()) {
					logger.info("channel.isClosed(): " + channel.isClosed());
					logger.info("channel.isEOF(): " + channel.isEOF());
					logger.info("exit-status: " + channel.getExitStatus());
					break;
				}

				try {
					Thread.sleep(1000);
					wait += 1000;
					logger.info("wait 1000");
				} catch (Exception ee) {
					ee.printStackTrace();
				}

			}// end while
		} catch (Exception e) {
			logger.error("Exception while getResult()", e);
			this.result = new StringBuffer();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (extIs != null) {
					extIs.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return this.result.toString();
	}

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

	public boolean isExistDir(String dir) {
        boolean success = true;
        this.doCommand("cd " + dir + "\n");
        try {
            InputStream in = channel.getInputStream();
            int nextChar;
            while (true) {
                while ((nextChar = in.read()) != -1) {
                    result.append((char) nextChar);
                }
                if (channel.isClosed()) {
                    if (channel.getExitStatus() != 0) {
                        success = false;
                    }
                    in.close();
                    break;
                }
                try {
                    Thread.sleep(500);
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }
        } catch (Exception e) {
            this.result = new StringBuffer();
            e.printStackTrace();
        }
        return success;
	}

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

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

	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 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 int childCountOfDir(String dir) {
		int count = 0;
		try {
			if (this.isExistDir(dir)) {
				this.doCommand("cd " + dir + ";ls -l | wc -l");
				String result = this.getResult();
				count = Integer.valueOf(result.trim()).intValue() - 1;
			} else {
				count = -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			count = -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();
						System.out.println("creat path=" + path);
					}
					if (!this.isExistDir(path)) {
						System.out.println("cat not creat path=" + path);
						return false;
					}
				}
			}
			if (this.isExistDir(dir)) {
				isExist = true;
			}
		}
		return isExist;
	}

	public String executeCommand(String command) throws Exception {
		return "";
	}

	public String executeCommand(List<String> commandList) throws Exception {
		return "";
	}

	public RomoteController cloneObject() {
		return null;
	}

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

	public String getError() {
		return error;
	}

	public static void main(String[] args) {
		SSHThread tt = new SSHThread("172.21.0.31", 22, "bnms", "bnms1");
		tt.initial();
		// ss.doCommand("cd /bnmsapp2/lianlian/masteragent/bin/; ksh startagent.sh");
		// String startAgentMsg = ss.getResult();
//		tt.doCommand("ls");
//		System.out.println(tt.getResult());
//		System.out.println(tt.isAuthorized());
		tt.close();
	}
}