To connect to an SSH server using JSch (Java Secure Channel), you need to perform the following steps:
Steps to Connect to SSH Server Using JSch
- Add the JSch library to your project dependencies.
- If using Maven, add the following dependency:
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
- If not using a dependency manager, download
jsch.jar
and add it to your project’s classpath.
- Write the code to establish an SSH connection. Here is an example code snippet:
package org.kodejava.jsch;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHConnectionExample {
public static void main(String[] args) {
String host = "example.com"; // Replace with SSH server address
String username = "username"; // Replace with username
String password = "password"; // Replace with password
int port = 22; // Default SSH port
JSch jsch = new JSch();
Session session = null;
try {
// Create Session object
session = jsch.getSession(username, host, port);
// Set password
session.setPassword(password);
// Configure session to avoid asking for key confirmation
session.setConfig("StrictHostKeyChecking", "no");
// Connect to the server
System.out.println("Connecting to " + host);
session.connect();
System.out.println("Connected successfully!");
// Your code to execute commands or perform actions can go here.
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isConnected()) {
session.disconnect();
System.out.println("Disconnected from server.");
}
}
}
}
Explanation
-
JSch Instance:
- Create an instance of
JSch
.
- Create an instance of
- Session:
- Use the
jsch.getSession
method to create a session object with the necessary credentials: host, username, and port.
- Use the
- Set Password:
- Use the
setPassword
method to provide the SSH server password.
- Use the
- Disable Strict HostKey Checking (Optional):
- By default, JSch checks the host key of the server during the first connection. You can disable this check using:
session.setConfig("StrictHostKeyChecking", "no");
- Note: Disabling this for production environments can reduce security, so use it cautiously.
- Connect:
- Call
session.connect()
to establish the SSH connection.
- Call
- Perform Actions:
- After connecting, you can now execute commands on the server using a
Channel
.
- After connecting, you can now execute commands on the server using a
- Clean Up:
- Always disconnect the session when done using the
session.disconnect()
method.
- Always disconnect the session when done using the
- Connect:
Example with Command Execution
If you want to execute a remote command on the server after connecting:
package org.kodejava.jsch;
import com.jcraft.jsch.*;
import java.io.InputStream;
public class ExecuteSSHCommand {
public static void main(String[] args) {
String host = "example.com";
String username = "username";
String password = "password";
int port = 22;
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
try {
// Create session and set credentials
session = jsch.getSession(username, host, port);
session.setPassword(password);
// Disable strict host key checking
session.setConfig("StrictHostKeyChecking", "no");
// Connect to the server
System.out.println("Connecting to " + host);
session.connect();
System.out.println("Connected successfully!");
// Open a shell/channel to execute a command
channel = session.openChannel("exec");
// Specify the command you want to execute
((ChannelExec) channel).setCommand("ls -la");
// Capture the command's output
InputStream input = channel.getInputStream();
channel.connect();
System.out.println("Command executed!");
// Read and print the command output
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0) {
System.out.print(new String(buffer, 0, read));
}
input.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channel != null && channel.isConnected()) {
channel.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
System.out.println("Disconnected from server.");
}
}
}
Tips
- Replace placeholders like
example.com
,username
, andpassword
with actual credentials. - Always handle exceptions to prevent runtime crashes.
- In production setups, manage SSH key authentication instead of plain passwords for enhanced security.