My linux world » Java – SSH Client

Java - SSH Client


Contents

Using JSCH

Dependencies

If you use maven, add this to your pom.xml :

<dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.53</version>
</dependency>

Session

Open session

Properties config = new Properties(); 
config.put("StrictHostKeyChecking", "no");
 
JSch jsch = new JSch();
session=jsch.getSession(login, hostname, port);
 
session.setPassword(password);
session.setConfig(config);
session.connect();

Close session

if(session != null && session.isConnected()) {
  session.disconnect();
}

Channel

Run command

ChannelExec channel=(ChannelExec) session.openChannel("exec");
BufferedReader reader=new BufferedReader(new InputStreamReader(channel.getInputStream()));		
channel.setCommand(command);
channel.setErrStream(System.err);
channel.setInputStream(null);
channel.connect();			
 
String line;
while ((line = reader.readLine()) != null) {
	System.out.println(line);
}
 
channel.disconnect();

Send File

ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
 
channel.put(new ByteArrayInputStream(sourceFile.getBytes()), destinationFile);
channel.disconnect();

Read File

ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
 
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = c.get(filePath);
 
try {
   byte[] buffer = new byte[256];
   int count;
   while (-1 != (count = is.read(buffer))) {
     bos.write(buffer, 0, count);
   }
} finally {
  IoUtils.closeQuietly(is);
}
 
channel.disconnect();
return new String(bos.toByteArray());

Using Apache Mina

Dependencies

If you use maven, add this to your pom.xml :

<dependencies>
  <dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>${apache-mina.version}</version>
  </dependency>
</dependencies>

Session

Open session

try(SshClient client = SshClient.setUpDefaultClient()) {
  client.start();
 
  session = client.connect(login, hostname, port)
  		  .verify(7L, TimeUnit.SECONDS)
		  .getSession();
 
  session.addPasswordIdentity(password);
  session.auth().verify(5L, TimeUnit.SECONDS);
}
catch (IOException e) {
  LOGGER.debug("Open SSH Session",e);
}

Close session

if(session != null && session.isOpen()) {
  session.close(true);
}

Channel

Run command

String response = session.executeRemoteCommand(command,stderr,Charset.defaultCharset());

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.