Java利用ssh工具远程执行shell脚本

1.首先下载ganymed-ssh2.jar   http://www.ganymed.ethz.ch/ssh2

2.SSHUtil工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SSHUtil {
	Connection conn = null;
	Session session = null;
	InputStream stdout = null;
	BufferedReader br = null;

	public SSHUtil(String hostname, String username, String password) {
		try {
			conn = new Connection(hostname);
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(username, password);
			if (isAuthenticated == false) {
				throw new IOException("Authentication failed.");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		if (session != null) {
			session.close();
		}
		if (conn != null) {
			conn.close();
		}
	}

	public void closeSession() {
		session.close();
	}

	public void execCommand(String command) throws IOException {
		session = conn.openSession();
		session.execCommand(command);
		stdout = new StreamGobbler(session.getStdout());
		br = new BufferedReader(new InputStreamReader(stdout));
	}

	public String readLine() throws IOException {
		return br.readLine();
	}
}

3.使用方法(执行tail命令,查看日志文件)

SSHUtil ssh;
try {
	ssh = new SSHUtil(ip, user, password);
	ssh.execCommand("tail -f " + " " + logFile);
	while (true) {
		String line = ssh.readLine();
		System.out.println("line>>>:" + line);
		if (line == null || channel.getSubscriberCount() == 0) {
			break;
		}
		channel.publish(client, line, null);
	}
} catch (IOException e) {
	e.printStackTrace();
	throw new RuntimeException(e);
} finally {
	ssh.close();
}



你可能感兴趣的:(Java)