java 操作ssh下令

java 操作ssh命令

java 操作ssh命令

 

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;


public class Shell1 {
	public static void main(String[] args) {
		String str = Shell1
				.sshExecute("192.168.9.52", "hadoop", "hadoop", "ls");
		System.out.println(str);
	}

	public static abstract class MyUserInfo implements UserInfo,
			UIKeyboardInteractive {
		public String getPassword() {
			return null;
		}

		public boolean promptYesNo(String str) {
			return false;
		}

		public String getPassphrase() {
			return null;
		}

		public boolean promptPassphrase(String message) {
			return false;
		}

		public boolean promptPassword(String message) {
			return false;
		}

		public void showMessage(String message) {
		}

		public String[] promptKeyboardInteractive(String destination,
				String name, String instruction, String[] prompt, boolean[] echo) {
			return null;
		}
	}

	public static String sshExecute(String host, String user, String pwd,
			String command) {
		// ps -ef|grep tomcat|grep -v grep|awk '{print $2}'
		StringBuffer sb = new StringBuffer();
		try {
			JSch jsch = new JSch();


			Session session = jsch.getSession(user, host, 22);
			session.setPassword(pwd);
			UserInfo ui = new MyUserInfo() {
				public void showMessage(String message) {
				}

				public boolean promptYesNo(String message) {
					return true;
				}
			};
			session.setUserInfo(ui);
			session.connect();
			Channel channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(command);
			InputStream in = channel.getInputStream();
			channel.connect();
			int nextChar;
			while (true) {
				while ((nextChar = in.read()) != -1) {
					sb.append((char) nextChar);
				}
				if (channel.isClosed()) {
					System.out.println("exit-status: "
							+ channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}
			channel.disconnect();
			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();

	}
}