Question : Problem: How can I get command output from j2ssh client ?

Hello,

I am writing a j2ssh client which reads scripts to be run via ssh for health checks etc.  I have an SSHWrapper class which looks after connetion, authetication etc and also have an execute_command function which is to be user to pass commands to the ssh server and cache the response.  The problem is the authentication works fine,  however when I pass a simple command such as ls -ltr to server,  I get ni response.  Please see all code and output below.  Any help greatly appreciated.  Thanks
Code Snippet:
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:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
package com;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
 
public class SshExample {
	
 
	
	  public static void main(String args[]) {
 
		  
		  		SSHWrapper ssh = new SSHWrapper();
		  		ssh.hostprompt="";
		  		ssh.hostname="iechbe15";
		  		ssh.username="tibco";
		  		ssh.password="eaiprd00";
		  		ssh.connect();
		  		ssh.execute_command("ls -ltr\n");
		  		
		  		ssh.disconnect();
		  		
		  
		  		
		    	
				return;
				
	    	
	  }	
 
}
 
 
 
package com;
 
import com.sshtools.j2ssh.SshClient; 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;   
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;  
import com.sshtools.j2ssh.session.SessionChannelClient;
 
public class SSHWrapper {
	
 
	  String hostname;
	  String hostprompt;
	  String username;
	  String password;
	  String response;
   	  SshClient ssh;
   	  SessionChannelClient session;
   	  
   	// A buffered reader so we can request information from the user
	  private static BufferedReader reader =
	        new BufferedReader(new InputStreamReader(System.in));
 
	SSHWrapper(){
		hostname="";
		username="";
		password="";
		
	}
 
	
	  public String  connect() {
 
		  String return_value="";
		  String command = "ls -ltr\n";
		  int result=0;
		  boolean prompt_returned=false;
		  
		  try {
 
	    	// Create the new  client 
			ssh = new SshClient();
			return_value="created connection successfuly...";
 
			//connect to the host
	    	ssh.connect(hostname);	   
			return_value="Connected to " + hostname + "successfully...";
 
			/** 
	    	  * Create a PasswordAuthenticationClient instance, set the properties
	    	  * and pass to the SessionClient to authenticate
	    	  */
	    	  PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
	    	  
	    	  pwd.setUsername(this.username);
	    	  pwd.setPassword(this.password);
	    	
	    	  result = ssh.authenticate(pwd);
	    	  return_value = "Login result = " + result;
	    	  
	    	  if(result==AuthenticationProtocolState.FAILED)
	    		     return_value = "The authentication failed";
 
    		  if(result==AuthenticationProtocolState.PARTIAL)
    			  return_value = "The authentication succeeded but another"
	    			                   + "authentication is required";
 
    		  if(result==AuthenticationProtocolState.COMPLETE)
    			  return_value = "The authentication is complete";
    		  
    		  session = ssh.openSessionChannel();
    		  return_value = "session is open successfully...";
    		  
    		  session.requestPseudoTerminal("vt100", 80, 25, 0, 0 , "");
    		  session.startShell();
 
    		  
    		  return_value = "shell started successfully...";
 
    		  
    		  return return_value;
	    	
		} catch(Exception e) {
	      return_value = return_value + "   " + e.getStackTrace();
	      return return_value;
	    }
	  }	
 
	  
	  
	  public String  disconnect() {
 
		  String return_value="";
		  
		  try {
 
	    	// Create the new  client 
    		session.close();
    		reader.close();
    		return_value = "Session closed successfully...";
    		  
    		  return return_value;
	    	
		} catch(Exception e) {
			return_value = return_value + "   " + e.getStackTrace();
			return return_value;
	    }
	  }	
	  
 
	  public String  execute_command(String command ) {
 
		  String return_value="";
		  boolean prompt_returned=false;
		  
		  try {
 
			  response = "";
			  return_value = "Executing command : " + command;
			  System.out.println(return_value);
			  /** Writing to the session OutputStream */
    		  OutputStream out = session.getOutputStream();
    		  out.write(command.getBytes());
    		  
    		  /**
    		  * Reading from the session InputStream
    		  */
    		  InputStream in = session.getInputStream();
    		  byte buffer[] = new byte[255];
    		  int read;
    		  return_value += " : Response=";
    		  while( prompt_returned==false && (read = in.read(buffer))>0 ) {
    			  System.out.println("prompt_returned="+prompt_returned + " / read=" + read);
    			  prompt_returned=false;
    		     response = new String(buffer, 0, read);
    		     return_value += response.toString();
    		     System.out.println(response);
    		     
    		     if ( response.indexOf(this.hostprompt) >= 0 )
    		    	 prompt_returned=true;
    		     
    		  }
    		  return return_value;
	    	
		} catch(Exception e) {
			return_value = return_value + "   " + e.getStackTrace();
			return return_value;
	    }
	  }	
 
	  
	public String getpassword() {
		return this.password;
	}
 
	public void setpassword(String input_value) {
		this.password = input_value;
	}
	  
 
	public String gethostname() {
		return this.hostname;
	}
 
	public void sethostname(String input_value) {
		this.hostname = input_value;
	}
 
	public String getusername() {
		return this.username;
	}
 
	public void setusername(String input_value) {
		this.username = input_value;
	}
 
	
	public String gethostprompt() {
		return this.hostprompt;
	}
 
	public void sethostprompt(String input_value) {
		this.hostprompt = input_value;
	}
	
}
 
18-Aug-2008 16:05:23 com.sshtools.j2ssh.transport.publickey.SshKeyPairFactory 
INFO: Loading public key algorithms
18-Aug-2008 16:05:24 com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: JAVA version is 1.5.0_06
18-Aug-2008 16:05:24 com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension C:\Sun\AppServer\jdk\jre\lib\ext\dnsns.jar being added to classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding C:\Sun\AppServer\jdk\jre\lib\ext\dnsns.jar to the extension classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension C:\Sun\AppServer\jdk\jre\lib\ext\localedata.jar being added to classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding C:\Sun\AppServer\jdk\jre\lib\ext\localedata.jar to the extension classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension C:\Sun\AppServer\jdk\jre\lib\ext\sunjce_provider.jar being added to classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding C:\Sun\AppServer\jdk\jre\lib\ext\sunjce_provider.jar to the extension classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension C:\Sun\AppServer\jdk\jre\lib\ext\sunpkcs11.jar being added to classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding C:\Sun\AppServer\jdk\jre\lib\ext\sunpkcs11.jar to the extension classpath
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.cipher.SshCipherFactory 
INFO: Loading supported cipher algorithms
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.kex.SshKeyExchangeFactory 
INFO: Loading key exchange methods
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.compression.SshCompressionFactory 
INFO: Loading compression methods
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.hmac.SshHmacFactory 
INFO: Loading message authentication methods
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolCommon startTransportProtocol
INFO: Starting transport protocol
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolCommon run
INFO: Registering transport protocol messages with inputstream
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolCommon negotiateVersion
INFO: Negotiating protocol version
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolCommon negotiateVersion
INFO: Protocol negotiation complete
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolCommon beginKeyExchange
INFO: Starting key exchange
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.kex.DhGroup1Sha1 performClientExchange
INFO: Starting client side key exchange.
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification verifyHost
INFO: Verifying iechbe15,10.162.123.114 host key
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolClient verifyHostKey
INFO: The host key signature is  valid
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.TransportProtocolCommon completeKeyExchange
INFO: Completing key exchange
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.cipher.SshCipherFactory newInstance
INFO: Creating new blowfish-cbc cipher instance
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.cipher.SshCipherFactory newInstance
INFO: Creating new blowfish-cbc cipher instance
18-Aug-2008 16:05:24 com.sshtools.j2ssh.connection.ConnectionProtocol onServiceInit
INFO: Registering connection protocol messages
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.Service start
INFO: ssh-connection has been requested
18-Aug-2008 16:05:24 com.sshtools.j2ssh.transport.AsyncService onStart
INFO: Starting ssh-connection service thread
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol openChannel
INFO: Channel 0 is open [session]
18-Aug-2008 16:05:25 com.sshtools.j2ssh.session.SessionChannelClient requestPseudoTerminal
INFO: Requesting pseudo terminal
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol sendChannelRequest
INFO: Sending pty-req request for the session channel
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol sendChannelRequest
INFO: Waiting for channel request reply
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol sendChannelRequest
INFO: Channel request succeeded
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol sendChannelRequest
INFO: Sending shell request for the session channel
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol sendChannelRequest
INFO: Waiting for channel request reply
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol sendChannelRequest
INFO: Channel request succeeded
Executing command : ls -ltr
 
prompt_returned=false / read=146
Last   successful login for tibco: Mon Aug 18 16:04:59 GMT0BST 2008  
Last unsuccessful login for tibco: Tue Aug 12 09:23:15 GMT0BST 2008      
 
18-Aug-2008 16:05:25 com.sshtools.j2ssh.connection.ConnectionProtocol closeChannel
INFO: Local computer has closed channel 0[session]
Open in New Window Select All

Answer : Problem: How can I get command output from j2ssh client ?

Hello,

I have found a solution to this,  and in the interest of open source and since I have found the site very helpful in the past,  here is the SSHWrapper which can be used,  implementing a task timeout sleep inorder to terminate the read should it not return.

package com;

import com.jscape.inet.ssh.*;
import com.jscape.inet.ssh.util.SshParameters;
import java.io.*;

public class SSHWrapper extends SshAdapter {
   
    private String sshHost;
    private String sshUserName;
    private String sshPassword;
    private String sshPrompt;
    private Ssh ssh = null;
    private SshScript script = null;
    private OutputStream output = null;
    private static BufferedReader reader = null;
    private int num_tasks;
    private SshParameters sshParams;
    private SshTask [] commandTask;
    private int max_command_tasks;
    private boolean force_immediate_execution;
    private String response;
   
   
    SSHWrapper(){
          sshHost="";
          sshUserName="";
          sshPassword="";
          sshPrompt="";
          num_tasks=0;
          max_command_tasks=500;
          commandTask = new SshTask[max_command_tasks];
          int i = 0;
          force_immediate_execution=false;
          response = "";
          
          for ( i = 0 ; i < max_command_tasks; i++)
                commandTask[i] = new SshTask("","","");                

    }

    public String setup() throws IOException, SshException  {
          
          String return_value = "";
          
          try {
                
                System.out.println("Connecting to " + sshHost + " as " + sshUserName + "/" + sshPassword);
              sshParams = new SshParameters(sshHost,sshUserName,sshPassword);
              ssh = new Ssh(sshParams);

              // register for events
              ssh.addSshListener(this);
              // create new script
              script = new SshScript(ssh);
              
              return_value = "Setup successful";

          }catch( Exception ex){
                return_value = "Connection failed with following exception : " + ex.getMessage();
              return return_value;
          }
          return return_value;
    }
   

   

    public String build_script( ) throws IOException, SshException  {
          
          String return_value = "";
          int i = 0;
          
          try {
                System.out.println("Building script for " + num_tasks + " tasks ");
                for ( i = 0 ; i < num_tasks; i ++ )
                  script.addTask(commandTask[i]);
                return_value = "Script built successfully : "  + num_tasks + " in total ";

          }catch( Exception ex){
                return_value = "Script build failed with following exception : " + ex.getMessage();
              return return_value;
          }
          return return_value;
    }
   

    public String add_command( String command) throws IOException, SshException  {
          
          String return_value = "";
          
          try {
                System.out.println("Adding the following command to script : " + command);
                if ( ! force_immediate_execution )
                      commandTask[num_tasks] = new SshTask(sshPrompt,command,sshPrompt);
                else
                      commandTask[num_tasks] = new SshTask(null,command,sshPrompt);
                      
                num_tasks++;
                return_value = "Command added successfully : " + command + " / total_commands = " + num_tasks;

          }catch( Exception ex){
                return_value = "Addition of command failed with following exception : " + ex.getMessage();
              return return_value;
          }
          return return_value;
    }

   
    public String connect_and_execute_script( ) throws IOException, SshException  {
          
          String return_value = "";
          int i = 0;
          
          try {
                System.out.println("Connecting and executing script");

                // connect to SSH server and execute script
            ssh.connect();
           
            // wait until last task is complete
            while(i < num_tasks && !commandTask[num_tasks].isComplete()) {
                try {
                      //System.out.println("Executing : " + commandTask[i].getCommand());
                   
                    Thread.sleep(15000);
                } catch(Exception e) {}
                i++;
               
            }

            return_value = "Script executed successfully : "  + num_tasks + " in total ";

            // disconnect from server
            ssh.disconnect();
           
          }catch( Exception ex){
                return_value = "Script execution failed at i = " + i + " : " + ex.getMessage();
              return return_value;
          }
          return return_value;
    }
   
   
   
      /**
       * Invoked when SSH connection is established.
       *
       * @param event a SshConnectedEvent
       * @see SshConnectedEvent
       * @see Ssh#connect
       */
      public void connected(SshConnectedEvent event) {
            System.out.println("Connected to host: " + event.getHost());
      }

      /**
       * Invoked when SSH connection is released.
       * Disconnect can occur in many circumstances including IOException during socket
       * read/write or manually invoking the Ssh#disconnect method.
       *
       * @param event a SshDisconnectedEvent
       * @see SshDisconnectedEvent
       * @see Ssh#disconnect
       */
      public void disconnected(SshDisconnectedEvent event) {
            System.out.println("Disconnected from host: " + event.getHost());
      }

      /**
       * Invoked when data is received from Telnet server.
       *
       * @param event a SshDataReceivedEventode>
       * @see SshDataReceivedEvent
       */
      public void dataReceived(SshDataReceivedEvent event) {
            response+=event.getData();
            //System.out.print(response);
      }  
   

      public String  getsshHost ( ){
            return sshHost;
      }
      
      public void setsshHost ( String Input_Value){
            sshHost = Input_Value;
      }
      
      public String  getsshUsreName ( ){
            return sshUserName;
      }
      
      public void setsshUserName ( String Input_Value){
            sshUserName = Input_Value;
      }

      public String  getsshPassword ( ){
            return sshPassword;
      }
      
      public void setsshPassword ( String Input_Value){
            sshPassword = Input_Value;
      }

      public String  getsshPrompt ( ){
            return sshPrompt;
      }
      
      public void setsshPrompt ( String Input_Value){
            sshPrompt = Input_Value;
      }

      
      public boolean  getforce_immediate_execution ( ){
            return force_immediate_execution;
      }
      
      public void setforce_immediate_execution ( boolean Input_Value){
            force_immediate_execution = Input_Value;
      }

      public String  getresponse ( ){
            return response;
      }
      
      public void setresponse ( String Input_Value){
            response = Input_Value;
      }
      
      
      
      
}






Regards
Terry
Random Solutions  
 
programming4us programming4us