Overview

Apache Mina was used. In the past, there are many examples of ssh connection using Jsch on the Internet. But Jsch doesn't update anymore. This can be a security risk. Apache Mina is constantly updated, and the method used is almost similar to that of Jsch, so it can be replaced.

First of all, there weren't too many examples. The examples in Apache Mina were too poorly explained to work properly.

https://github.com/apache/mina-sshd

There are too many codes, and I just want to connect through ssh and do a shell command, but the code I found does not work.

https://www.baeldung.com/java-ssh-connection

Running the example here only works half way through. One line command line commands work fine. However, consecutive shell command input does not work.

You will get an error with "channel.open()" and "channel.waitFor(..").

The following is an example code that confirms the normal operation of the Shell Command.

 

Code Example

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Collections;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.util.io.input.NoCloseInputStream;
import org.apache.sshd.common.util.io.output.NoCloseOutputStream;
import org.springframework.web.socket.TextMessage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SshdMina {
	private static final ExecutorService executor = Executors.newCachedThreadPool();

	private static final int PIPE_STREAM_BUFFER_SIZE = 1024 * 100;
	final PipedInputStream sshClientInputStream = new PipedInputStream(PIPE_STREAM_BUFFER_SIZE);
	final PipedOutputStream sshClientOutputStream = new PipedOutputStream();
	private final PipedInputStream bizInputStream = new PipedInputStream(PIPE_STREAM_BUFFER_SIZE);
	private final PipedOutputStream bizOutputStream = new PipedOutputStream();

	public static void main(String[] args) throws Exception {
		new SshdMina().boot();
	}

	private SshdMina() throws IOException {
		sshClientInputStream.connect(bizOutputStream);
		sshClientOutputStream.connect(bizInputStream);
	}

	private void boot() throws Exception {
		final SshClient client = SshClient.setUpDefaultClient();
		client.start();
		final ConnectFuture connect = client.connect("your usename", "your ip address", 22);
		connect.await(5000L);
		final ClientSession session = connect.getSession();
		session.addPasswordIdentity("your password");
		session.auth().verify(5000L);

		final ChannelShell channel = session.createShellChannel();
		channel.setIn(new NoCloseInputStream(sshClientInputStream));
		channel.setOut(new NoCloseOutputStream(sshClientOutputStream));
		channel.setErr(new NoCloseOutputStream(sshClientOutputStream));

		channel.setPtyType("xterm-256color");
		channel.setEnv("LANG", "en_US.UTF-8");
		channel.open();

		beginRead();
		beginWriteStd();

		channel.waitFor(Collections.singleton(ClientChannelEvent.CLOSED), 0);
	}

	void beginRead() {
		executor.execute(() -> {
			final byte[] buffer = new byte[10240];
			String line = "";
			while (!Thread.currentThread().isInterrupted()) {
				try {
					while (bizInputStream.available() > 0) {
						int i = bizInputStream.read(buffer, 0, 1024);
						if (i < 0) {
							break;
						}
						line = new String(buffer, 0, i);
						System.out.println(line);
						System.out.flush();
					}

					try {
						Thread.sleep(100);
					} catch (Exception ee) {
					}
				
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	void beginWriteStd() {
		executor.execute(() -> {
			try {
				final Scanner in = new Scanner(System.in);
				while (!Thread.currentThread().isInterrupted()) {
					final String command = in.nextLine();

					bizOutputStream.write((command + "\n").getBytes());
					bizOutputStream.flush();
				}

				in.close();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		});
	}
}

 

build.gralde

implementation group: 'org.apache.sshd', name: 'sshd-core', version: '2.9.0'
implementation group: 'net.i2p.crypto', name: 'eddsa', version: '0.3.0'

 

Console Result

[root@control-plane ~]# pwd
18:38:28.166 [sshd-ClientInputStreamPump[31304]-thread-1] DEBUG org.apache.sshd.common.channel.Window - waitForSpace(Window[client/remote](ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22])) available: 2093782
18:38:28.166 [sshd-ClientInputStreamPump[31304]-thread-1] DEBUG org.apache.sshd.common.channel.Window - waitAndConsume(Window[client/remote](ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22])) - requested=4, available=2093782
18:38:28.166 [sshd-ClientInputStreamPump[31304]-thread-1] DEBUG org.apache.sshd.client.session.ClientSessionImpl - encode(ClientSessionImpl[root@/10.251.94.146:22]) packet #38 sending command=94[SSH_MSG_CHANNEL_DATA] len=13
18:38:28.166 [sshd-ClientInputStreamPump[31304]-thread-1] DEBUG org.apache.sshd.common.io.nio2.Nio2Session - writeBuffer(Nio2Session[local=/10.251.94.146:44560, remote=/10.251.94.146:22]) writing 44 bytes
18:38:28.167 [sshd-SshClient[3bd323e9]-nio2-thread-8] DEBUG org.apache.sshd.client.channel.ChannelShell - handleData(ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22]) SSH_MSG_CHANNEL_DATA len=1
p18:38:28.167 [sshd-SshClient[3bd323e9]-nio2-thread-8] DEBUG org.apache.sshd.client.channel.ChannelShell - handleData(ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22]) SSH_MSG_CHANNEL_DATA len=1
w18:38:28.168 [sshd-SshClient[3bd323e9]-nio2-thread-8] DEBUG org.apache.sshd.client.channel.ChannelShell - handleData(ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22]) SSH_MSG_CHANNEL_DATA len=3
18:38:28.168 [sshd-SshClient[3bd323e9]-nio2-thread-8] DEBUG org.apache.sshd.client.channel.ChannelShell - handleData(ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22]) SSH_MSG_CHANNEL_DATA len=7
d
/root
18:38:28.168 [sshd-SshClient[3bd323e9]-nio2-thread-8] DEBUG org.apache.sshd.client.channel.ChannelShell - handleData(ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22]) SSH_MSG_CHANNEL_DATA len=25
]0;root@control-plane:~18:38:28.168 [sshd-SshClient[3bd323e9]-nio2-thread-8] DEBUG org.apache.sshd.client.channel.ChannelShell - handleData(ChannelShell[id=0, recipient=0]-ClientSessionImpl[root@/10.251.94.146:22]) SSH_MSG_CHANNEL_DATA len=24
[root@control-plane ~]#
[root@control-plane ~]# ls -lrt

 

728x90

'Java Utility' 카테고리의 다른 글

[ENG][IPv4][IPv6]Using IP Checker  (0) 2022.11.02
[ENG][Math]Arithmetic calculator including parentheses  (0) 2022.05.26
12345···51
반응형

+ Recent posts