Executing tasks dynamically
Top  Previous  Next

Under certain conditions you may want to create and execute tasks on the fly. An example of such a situation might be when the command for the next task depends on the response of the previous task. Dynamic SshTask usually have a null start prompt value as they are not waiting on data from the SSH server. To illustrate we will use the following use case.

Example


The example below demonstrates the following use case:

1. Login to system
2. Execute "ls -al *.tmp" command to get all files ending in .tmp extension.
3. If response of command contains .tmp (indicating that files with .tmp extension exist) then issue command "rm *.tmp" to delete all temporary files.


import com.jscape.inet.ssh.util.*;
import com.jscape.inet.ssh.*;

public class SshScriptDynamic implements SshListener {
  
  public static void main(String[] args) {
    SshScriptDynamic session = new SshScriptDynamic();
  }
  
  public SshScriptDynamic() {
    Ssh ssh = null;
    try {
      // define SSH connection info

      String hostname = "10.0.0.2"
;
      String username = "jsmith"
;
      String password = "secret"
;
      String shellPrompt = "$"
;
      SshParameters sshParams = new SshParameters(hostname,username,password);
      
      // create new Ssh instance

      ssh = new Ssh(sshParams);
      
      // register this class to capture events

      ssh.addSshListener(this);
      
      // create script

      SshScript script = new SshScript(ssh);
      
      // create directory listing task and add to script

      SshTask lsTask = new SshTask(shellPrompt,"ls -al *.tmp"
,shellPrompt);
      script.addTask(lsTask);
      
      // establish connection and run script      

      ssh.connect();
      
      // wait until directory listing task is complete

      while(!lsTask.isComplete()) {
        Thread.sleep(100
);
      }
      
      // check response of directory listing task

      if(lsTask.getResponse().indexOf(".tmp"
) != -1) {
        
        // create new task to delete files ending with .tmp extension

        SshTask delTask = new SshTask(null,"rm *.tmp"
,shellPrompt);
        script.addTask(delTask);
        
        // wait until delete task is complete

        while(delTask.isComplete()) {
          Thread.sleep(100
);
        }
      }    
      
    } catch(Exception e) {
      e.printStackTrace();
    } finally {
      // disconnect from SSH server

      try {
        ssh.disconnect();
      } catch(Exception e) {
      }
    }
    
  }
  
  /**
   * Captures connected event
   */

  public void connected(SshConnectedEvent evt) {
    System.out.println("Connected"
);
  }
  
  /**
   * Captures data received event
   */

  public void dataReceived(SshDataReceivedEvent evt) {
    System.out.print(evt.getData());
  }
  
  /**
   * Captures disconnected event
   */

  public void disconnected(SshDisconnectedEvent evt) {
    System.out.println("Disconnected"
);
  }

}