3

I would like to know how to execute multiple commands using j2ssh. The code I got from the net is as follows:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.sshtools.j2ssh.io.IOStreamConnector;
import com.sshtools.j2ssh.io.IOStreamConnectorState;
import com.sshtools.j2ssh.connection.*;

import com.sshtools.j2ssh.SshClient;

import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.session.SessionChannelClient;

import com.sshtools.j2ssh.configuration.SshConnectionProperties;

import com.sshtools.j2ssh.transport.ConsoleHostKeyVerification;

public class MySSHClient {

  SshClient ssh = null;
  SshConnectionProperties properties = null;
  SessionChannelClient session = null;

  public MySSHClient(String hostName, String userName, String passwd )
  {

    try
    {
      // Make a client connection
      ssh = new SshClient();
      properties = new SshConnectionProperties();
      properties.setHost(hostName);

      // Connect to the host
      ssh.connect(properties, new ConsoleHostKeyVerification());

      // Create a password authentication instance
      PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();

      pwd.setUsername(userName);
      pwd.setPassword(passwd);

      // Try the authentication
      int result = ssh.authenticate(pwd);

      // Evaluate the result
      if (result==AuthenticationProtocolState.COMPLETE) {

        System.out.println("Connection Authenticated");
      }
    }
    catch(Exception e)
    {
      System.out.println("Exception : " + e.getMessage());
    }

  }//end of method.


  public String execCmd(String cmd)
  {
    String theOutput = "";
    try
    {
      // The connection is authenticated we can now do some real work!
      session = ssh.openSessionChannel();

      if ( session.executeCommand(cmd) )
      {
        IOStreamConnector output = new IOStreamConnector();
        java.io.ByteArrayOutputStream bos =  new
        java.io.ByteArrayOutputStream();
        output.connect(session.getInputStream(), bos );
        session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
        theOutput = bos.toString();
      }
      //else
      //throw Exception("Failed to execute command : " + cmd);
      //System.out.println("Failed to execute command : " + cmd);
    }
    catch(Exception e)
    {
      System.out.println("Exception : " + e.getMessage());
    }

    return theOutput;
  }


}

I tried to go to a directory then list the files using the ls command but it didn't work

MySSHClient sshc = new MySSHClient(<hostName>, <userName>, <passwd>);
System.out.println( sshc.execCmd("cd test") );
System.out.println( sshc.execCmd("ls") );

Any help please?

Philippe Blayo
  • 10,610
  • 14
  • 48
  • 65
Raoul
  • 331
  • 1
  • 6
  • 7
  • Do you know if it's not executing the command, or not outputting results (you execute then open the stream for the output). Try using a 'touch' command or similar to create a file on the remote host,and see if that works – Brian Agnew Dec 06 '12 at 11:18
  • @Brian Agnew it does execute the command and output the results but the problem is that it loses the directory and hence displays the contents of the previous directory itself – Raoul Dec 06 '12 at 11:23
  • accoruding to this link http://javaconfessions.com/2008/09/getting-started-with-j2ssh.html in the section "A word on executing multiple commands" it says you cannot for example execute a command to change directory and then another to execute a script in that directory, since the change directory is lost when the session closes and the new command starts back in the default working directory. Of course you could always put the cd command into the script? Or use the shell to execute both commands. what i didnt understand is how to use the script – Raoul Dec 06 '12 at 11:35

3 Answers3

0

Try separating commands by a semicolon. For example: System.out.println( sshc.execCmd("cd test; ls") );

Tim L
  • 1
0

Add the and operator (&&) between the commands:

System.out.println( sshc.execCmd("cd test && ls") );

&& is better than ; because if the cd fails the ls is not executed.

Philippe Blayo
  • 10,610
  • 14
  • 48
  • 65
0

Instead of using executeCommand, try to write your commands in output stream - session.getOutputStream() with '\n' addition on the end. Then read input stream.

For example:

session.getOutputStream().write((command + "\n").getBytes());
Waldo Jeffers
  • 2,289
  • 1
  • 15
  • 19
aleneox
  • 21
  • 2