Description : This program will explode the myapp.tar present in myHome directory and then navigation will be moved to “scripts” directory, generated after exploding the tar and then run “ls” command
Input : hostname,username, password
Output: output of each command will be printed to console
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
package com.coddicted.example; import java.io.InputStream; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class SSHCommandExecutor { Session session = null; Channel channel = null; String host = ""; String user = ""; String password = ""; String command1 = ""; JSch jsch = null; java.util.Properties config = null; SSHCommandExecutor() { this.host = "172.21.161.94"; this.user = "user"; this.password = "secret"; this.command1 = "ls -ltr"; } public Channel initializeSession() { try { config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); jsch = new JSch(); session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); System.out.println("Session Connected..."); return session.openChannel("exec"); } catch (Exception e) { e.printStackTrace(); return null; } } public void executeCommand(String command) { try { channel = initializeSession(); if (channel != null) { System.out.println("<<<<<<<<not null>>>>>>>>>>"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); readServerOutput(channel, in); in.close(); channel.disconnect(); session.disconnect(); System.out.println("DONE"); // System.exit(0); } else { System.out.println("Error occured..."); System.exit(0); } } catch (Exception e) { e.printStackTrace(); } } public void connectAndDeploy() { try { command1 = "cd myHome\n ls\n tar -xvf myyapp.tar\n"; executeCommand(command1); command1 = "cd myHome/scripts\n ls\n"; executeCommand(command1); } catch (Exception e) { e.printStackTrace(); } } public void readServerOutput(Channel channel, InputStream in) { byte[] tmp = new byte[1024]; try { while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) { break; } System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { SSHCommandExecutor sce = new SSHCommandExecutor(); sce.connectAndDeploy(); } } |