如何从Java类调用Unix脚本?JDK中JSch类缺失问题求助
Hey, let's clear this up first: the com.jcraft.jsch classes you're seeing in examples aren't part of any JDK release—they belong to a third-party SSH library called JSch, which is used for remote SSH connections and executing commands on Unix-like systems. That's why you can't find them in JDK 8 or any other JDK version. Here's how to fix this:
1. 引入JSch第三方库
Since JSch isn't bundled with the JDK, you need to explicitly add it to your project:
For Maven users:
Add this dependency to your pom.xml:
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> <!-- Use the latest stable version available --> </dependency>
For Gradle users:
Add this line to your build.gradle dependencies block:
implementation 'com.jcraft:jsch:0.1.55'
Manual Jar installation:
Download the JSch jar file from the Maven Central Repository, then add it to your project's classpath (e.g., in Eclipse: right-click project → Build Path → Add External Archives; in IntelliJ: Project Structure → Libraries → Add the jar).
2. Example: Execute a remote Unix script with JSch
Here's a basic working example to connect to a remote Unix server and run your script:
import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.ChannelExec; import java.io.InputStream; public class RemoteScriptRunner { public static void main(String[] args) { String remoteHost = "your-server-ip-or-hostname"; String username = "your-ssh-username"; String password = "your-ssh-password"; String scriptPath = "/home/user/scripts/your-script.sh"; JSch jsch = new JSch(); Session session = null; ChannelExec execChannel = null; try { // Create SSH session session = jsch.getSession(username, remoteHost, 22); session.setPassword(password); // Skip host key verification (not recommended for production; use proper key auth instead) java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // Connect to the server session.connect(); // Open an exec channel to run the script execChannel = (ChannelExec) session.openChannel("exec"); execChannel.setCommand("bash " + scriptPath); // Capture script output InputStream outputStream = execChannel.getInputStream(); execChannel.connect(); // Read and print the output byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = outputStream.read(buffer)) != -1) { System.out.print(new String(buffer, 0, bytesRead)); } // Wait for the script to finish while (!execChannel.isClosed()) { Thread.sleep(100); } // Print exit status of the script System.out.println("\nScript exit status: " + execChannel.getExitStatus()); } catch (JSchException | InterruptedException | java.io.IOException e) { e.printStackTrace(); } finally { // Clean up resources if (execChannel != null && execChannel.isConnected()) { execChannel.disconnect(); } if (session != null && session.isConnected()) { session.disconnect(); } } } }
3. Alternative: Execute a local Unix script (no remote needed)
If your script runs on the same machine as your Java application, you don't need JSch at all—use JDK's built-in ProcessBuilder instead:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LocalScriptRunner { public static void main(String[] args) { String localScriptPath = "/home/user/scripts/your-local-script.sh"; ProcessBuilder processBuilder = new ProcessBuilder("bash", localScriptPath); processBuilder.redirectErrorStream(true); // Merge stdout and stderr for easier reading try { Process process = processBuilder.start(); // Read script output BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // Wait for script completion and get exit code int exitCode = process.waitFor(); System.out.println("\nScript exit code: " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
内容的提问来源于stack exchange,提问作者siddharth sharma

