(1). OpenSSH是什么?

OpenSSH是SSH(Secure SHell)协议的免费开源实现.
说明白一点就是:我们平时用SSH登录Linux时,所使用的一套开源协议.
它能做什么?
比如:堡垒机/远程SH调用…

(2). 引入依赖

<dependency>
	<groupId>org.apache.sshd</groupId>
	<artifactId>sshd-core</artifactId>
	<version>1.2.0</version>
</dependency>

(3). 入门案例

import java.util.EnumSet;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.util.io.NoCloseInputStream;
import org.apache.sshd.common.util.io.NoCloseOutputStream;

public class Test {
	public static void main(String[] args) throws Exception {
		try (SshClient client = SshClient.setUpDefaultClient()) {
			client.start();
			try (ClientSession session = client.connect("lixin", "127.0.0.1", 22).verify(5000).getSession()) {
				// 密码模式
				session.addPasswordIdentity("xxxxxx");
				
				
				// 密钥模式
				// String resourceKey = "/Users/lixin/.ssh/id_rsa";
				// FileInputStream is = new FileInputStream(resourceKey);
				// KeyPair keyPair = SecurityUtils.loadKeyPairIdentity(resourceKey, is, null);
				
				// session.addPublicKeyIdentity(keyPair);
				
				session.auth().verify(10000);
				try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
					channel.setIn(new NoCloseInputStream(System.in));
					channel.setOut(new NoCloseOutputStream(System.out));
					channel.setErr(new NoCloseOutputStream(System.err));
					channel.open();
					channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
				} finally {
					session.close(false);
				}
			} finally {
				client.stop();
			}
		}
	}
}

(4). 总结

SSHD支持密码和密钥模式,同时:基于SSHD,阿里开源了一套:termd-core工具.