Backend Development 7 min read

Unlock Remote Server Access in Spring Boot 3 with JSch: Read Files & Run Commands

This article introduces the Java JSch library for Spring Boot 3, demonstrating how to read remote files without downloading, execute commands on a remote host, and obtain an interactive shell prompt, complete with Maven dependency setup, code examples, and execution results, while promising ongoing updates to the case collection.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Unlock Remote Server Access in Spring Boot 3 with JSch: Read Files & Run Commands

This article introduces the Java JSch library for Spring Boot 3, which enables Java applications to connect to remote servers for file access and command execution.

1. Introduction

The library allows reading files directly from a remote Linux host, executing arbitrary commands, and opening an interactive shell session.

Read remote files without downloading them locally.

Execute commands on the remote host.

Obtain a shell prompt for interactive use.

2. Practical Cases

Environment Preparation

Add the JSch dependency to your Maven project:

<code>&lt;dependency&gt;
    &lt;groupId&gt;com.github.mwiede&lt;/groupId&gt;
    &lt;artifactId&gt;jsch&lt;/artifactId&gt;
    &lt;version&gt;0.2.23&lt;/version&gt;
&lt;/dependency&gt;</code>

2.1 Read Remote Host File

Prepare a file pack.txt on the remote host (e.g., /root/jsch/pack.txt ) and read its content using JSch:

<code>private static final String USER = "root";
private static final String HOST = "192.168.1.188";
private static final int PORT = 22;
private static final String PASSWORD = "xxxooo001";</code>
<code>try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(USER, HOST, PORT);
    session.setPassword(PASSWORD);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
    sftpChannel.connect();
    InputStream inputStream = sftpChannel.get("/root/jsch/pack.txt");
    try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
    sftpChannel.disconnect();
    session.disconnect();
} catch (Exception e) {
    e.printStackTrace();
}</code>

The console output will display the file content, e.g.,

<code>xxxooo
Spring Boot3实战案例锦集100例</code>

2.2 Execute Remote Host Command

Run a command such as ls /root/software on the remote host:

<code>// Establish session (session variable must be initialized)
String command = "ls /root/software";
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
    while (in.available() > 0) {
        int i = in.read(tmp, 0, 1024);
        if (i < 0) break;
        System.out.print(new String(tmp, 0, i));
    }
    if (channel.isClosed()) {
        if (in.available() > 0) continue;
        break;
    }
    Thread.sleep(1000);
}
channel.disconnect();
session.disconnect();</code>

If the command is invalid (e.g., lls /root/software ), the console will show an error such as:

<code>bash: lls: command not found</code>

2.3 Get Shell Prompt

Open an interactive shell channel to obtain a prompt where users can type commands freely:

<code>try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(USER, HOST, PORT);
    session.setPassword(PASSWORD);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.setInputStream(System.in);
    channel.setOutputStream(System.out);
    channel.connect(3 * 1000);
} catch (Exception e) {
    e.printStackTrace();
}</code>

After connecting, the terminal displays a shell prompt, allowing you to execute any command on the remote host.

All examples are built with Spring Boot 3.4.0 and JSch 0.2.23, and the collection promises continuous updates with new cases.

Javabackend developmentSpring BootRemote ExecutionJSch
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.