Home > Java > javaTutorial > What Java SSH Libraries Exist, and How Can I Use JSCH for Secure Remote Connections?

What Java SSH Libraries Exist, and How Can I Use JSCH for Secure Remote Connections?

Susan Sarandon
Release: 2024-12-13 18:17:13
Original
606 people have browsed it

What Java SSH Libraries Exist, and How Can I Use JSCH for Secure Remote Connections?

SSH Libraries for Java

When connecting to remote servers using SSH, it's crucial to utilize a reliable library. In Java, one notable option is the Java Secure Channel (JSCH).

JSCH for SSH in Java

JSCH is a widely adopted open-source library that facilitates seamless SSH connections in Java applications. Its BSD-style license allows for both personal and commercial use.

Example Usage of JSCH for SSH Connections

import com.jcraft.jsch.*;

public class SSHConnection {

    public static void main(String[] args) throws JSchException {
        // Replace user, host, and port with your own server details
        String user = "username";
        String host = "server.example.com";
        int port = 22;

        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.connect();

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand("ls -la");
        channel.connect();

        InputStream in = channel.getInputStream();
        byte[] result = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(result, 0, 1024);
                if (i < 0) {
                    break;
                }
                System.out.print(new String(result, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("Exit status: " + channel.getExitStatus());
                break;
            }
        }

        channel.disconnect();
        session.disconnect();
    }
}
Copy after login

This code sample demonstrates how to establish an SSH connection to a remote server, execute a command, and display the output using JSCH.

The above is the detailed content of What Java SSH Libraries Exist, and How Can I Use JSCH for Secure Remote Connections?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template