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(); } }
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!