![JAR search and dependency download from the Maven repository](/logo.png)
zed.ssh.client.SshClient Maven / Gradle / Ivy
The newest version!
package zed.ssh.client;
import com.jcraft.jsch.*;
import java.io.*;
import java.util.List;
public class SshClient {
// Constants
private static final int DEFAULT_SSH_PORT = 22;
// Configuration members
private final String host;
private final int port;
private final String username;
private final String password;
// Constructors
public SshClient(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
public SshClient(String host, String username, String password) {
this(host, DEFAULT_SSH_PORT, username, password);
}
public List command(String command) {
ListSshClientOutputCollector outputCollector = new ListSshClientOutputCollector();
command(command, outputCollector);
return outputCollector.lines();
}
public void printCommand(String command) {
command(command, new StdoutSshClientOutputCollector());
}
public void command(String command, SshClientOutputCollector outputCollector) {
Session session = null;
Channel channel = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
String msg = null;
while ((msg = in.readLine()) != null) {
outputCollector.collect(msg);
}
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException jsche) {
throw new RuntimeException(jsche);
} finally {
if (channel != null) {
channel.disconnect();
session.disconnect();
}
}
}
public void scp(InputStream inputStream, File destination) {
Session session = null;
Channel channel = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.cd(destination.getParent());
channelSftp.put(inputStream, destination.getName());
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException jsche) {
throw new RuntimeException(jsche);
} finally {
if (channel != null) {
channel.disconnect();
session.disconnect();
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy