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();
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值