Home >Java >javaTutorial >How to Connect to an SSH Server Using Java's JSCH Library?

How to Connect to an SSH Server Using Java's JSCH Library?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 22:06:18493browse

How to Connect to an SSH Server Using Java's JSCH Library?

Connecting to SSH Using Java

SSH, or Secure Shell, is a powerful tool for securely connecting to remote servers. In Java, there are multiple SSH libraries available to help you establish and manage SSH connections.

One of the most well-renowned Java SSH libraries is the Java Secure Channel (JSCH) library. Its popularity stems from its use in various Java-based tools and applications, including Maven, Ant, and Eclipse. It is an open-source library distributed under a BSD style license.

Example:

To connect to an SSH server using JSCH:

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SSHConnection {

    public static void main(String[] args) throws Exception {
        // SSH server hostname
        String hostname = "example.com";
        // SSH server port
        int port = 22;
        // SSH username
        String username = "username";
        // SSH password
        String password = "password";

        JSch jsch = new JSch();

        // Create a new SSH session
        Session session = jsch.getSession(username, hostname, port);
        session.setPassword(password);

        // Connect to the SSH server
        session.connect();

        // SSH command execution (optional)
        // Execute a remote command on the server
        String command = "ls -l";
        String result = session.execCommand(command).getStdOut();
        System.out.println(result);

        // Disconnect from the SSH server
        session.disconnect();
    }
}

This code snippet demonstrates how to establish an SSH connection, execute a remote command, and retrieve its output using the JSCH library in Java.

The above is the detailed content of How to Connect to an SSH Server Using Java's JSCH Library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn