Hello folks,
I am very new to JAVA and trying to learn the same.
I need to write a scenario where I need to pass the command to remote server and execute it there and fetch the result. I searched the google and got multiple post on same and I tried one of the code which worked for me fine. Please find below the same code:
package eclipsepackage; import java.io.IOException; import java.io.InputStream; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class VE_GetDetails_1 { public static void main(String[] args) throws JSchException, IOException{ // TODO Auto-generated method stub System.out.println("Hello"); String sUsername = "<uname>"; String sPassword = "<pwd>"; String sSMS1 = "<IP address>"; String sCMD = "<cmd>"; JSch jsch = new JSch(); Session session = null; session = jsch.getSession(sUsername, sSMS1, 22); session.setConfig("StrictHostKeyChecking", "no"); //authenticity no session.setPassword(sPassword); session.connect(); ChannelExec channel1 = (ChannelExec) session.openChannel("exec"); channel1.setCommand(sCMD); channel1.setInputStream(null); ((ChannelExec) channel1).setErrStream(System.err); InputStream in = channel1.getInputStream(); // gets data from InputStream created !!! channel1.connect(); // System.out.println("SMS system connected..."); System.out.println("Console Output for command " + sCMD); PrintConsoleOutput(in,channel1); channel1.disconnect(); } public static void PrintConsoleOutput(InputStream in, ChannelExec channel) throws IOException { System.out.println("-----------------------------------------------------"); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); /* Number of bytes actually read is returned as an integer. */ if (i < 0) { break; } String line = new String(tmp, 0, i); /* String(char chars[ ], int startIndex, int numChars) Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3); This initializes s with the characters cde. */ System.out.println(line); } if (channel.isClosed()) { break; } try { Thread.sleep(1000); } catch (Exception ee) { //ignore } } } }
I tried to understand the code, but didnt get which command really triggering/executing the required linux command on remote host.
getinputstream will fetch the byte data i.e. the result, but which command really executing on remote host?
PLease let me know !!! and if possible, please help me in understanding the channel flow !!
Thanks,
Asif Masood