日期:2014-05-16  浏览次数:20831 次

使用JSCH连接Linux服务器(1)-执行linux命令
在java中可以使用jsch连接远程Linux服务器,并在服务器上执行传送命令,同时该jar包也可以使用ftp在服务器上上传下载文件,本节讲述如何通过该jar包传送linux命令并且执行:
package com.aliyun.utility.jsch;

import java.io.InputStream;
import java.util.Properties;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JSCHUtil {
	private static JSCHUtil instance;

	public static JSCHUtil getInstance() {
		if (instance == null) {
			instance = new JSCHUtil();
		}
		return instance;
	}

	private JSCHUtil() {

	}

	private Session getSession(String host, int port, String ueseName)
			throws Exception {
		JSch jsch = new JSch();
		Session session = jsch.getSession(ueseName, host, port);
		return session;
	}

	public Session connect(String host, int port, String ueseName,
			String password) throws Exception {
		Session session = getSession(host, port, ueseName);
		session.setPassword(password);
		Properties config = new Properties();
		config.setProperty("StrictHostKeyChecking", "no");
		session.setConfig(config);
		session.connect();
		return session;
	}

	public String execCmd(Session session, String command) throws Exception {
		if (session == null) {
			throw new RuntimeException("Session is null!");
		}
		ChannelExec exec = (ChannelExec) session.openChannel("exec");
		InputStream in = exec.getInputStream();
		byte[] b = new byte[1024];

		exec.setCommand(command);
		exec.connect();
		StringBuffer buffer = new StringBuffer();
		while (in.read(b) > 0) {
			buffer.append(new String(b));
		}
		exec.disconnect();

		return buffer.toString();
	}

	public void clear(Session session) {
		if (session != null && session.isConnected()) {
			session.disconnect();
			session = null;
		}
	}

	public static void main(String[] args) throws Exception {
		Session session = JSCHUtil.getInstance().connect("10.9.9.135", 22,
				"yy", "yy");
		String cmd = "cd /" + ";" + "ls -al |grep home";
		String result = JSCHUtil.getInstance().execCmd(session, cmd);// 多条命令之间以;分隔
		System.out.println(result);
		System.exit(0);
	}
}