To execute ssh command in Linux, we need to use java API to run command at Unix machine. java ssh API is required to run linux commands through ssh with user Authentication.
This example will explain how to execute ssh in java.
Download ganymed ssh jar and set classpath before running program
import java.io.*; import ch.ethz.ssh2.*; public class JavaRunSshCommandExample { public static void main(String[] args) { String hostname = "127.0.0.1"; String username = "root"; String password = "password"; boolean isAuthenticated = false; try { Connection conn = new Connection(hostname); conn.connect(); isAuthenticated=conn.authenticateWithPassword(username, password); if (isAuthenticated == false) throw new IOException("Authentication failed."); Session sess = conn.openSession(); sess.execCommand("cd /;ls -l> out.txt"); InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stderr = new StreamGobbler(sess.getStderr()); InputStreamReader insrout=new InputStreamReader(stdout); InputStreamReader insrerr=new InputStreamReader(stderr); BufferedReader stdoutReader = new BufferedReader(insrout); BufferedReader stderrReader = new BufferedReader(insrerr); while (true) { String line = stdoutReader.readLine(); if (line == null) { break; } System.out.println(line); } while (true) { String line = stderrReader.readLine(); if (line == null) { break;} System.out.println(line); } sess.close(); conn.close(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(2); } } }
Other java ssh api
Tags: Java





Link to Us