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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3