简体   繁体   中英

Using specific command output of JSch to trigger next command

Using the following code:

public static void main(String[] args) throws Exception
{
  JSch jsch = new JSch();
  String user = "XXXXX";       
  String host = "XXXXX"; 
  String passwd = "XXXXX";      
  int port = 22;    
  Session session = jsch.getSession(user, host, port);
  session.setPassword(passwd);
  session.setConfig("StrictHostKeyChecking", "no");
  session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
  session.connect();

  Channel channel = session.openChannel("shell");
  OutputStream ops = channel.getOutputStream();
  PrintStream ps = new PrintStream(ops, true);

  channel.connect();

  //commands
  ps.println("sudo su - user");
  ps.println("ls | wc -l");

  ps.println("pwd");

  ps.println("exit");
  ps.close();

  channel.disconnect();
  session.disconnect();
 }  

for this kind of code, is it possible:

  1. Get the output for each command fired on the console individually.
  2. Use a control statement depending upon the previous output.

eg: If I use

ls | wc -l

The output would be a fixed digit as the directories in root wouldn't change. Using this number to either process step a or b using if/else condition.

I wrote this awhile ago, but I did it a little differently then how you have it setup. It grabs the returns how you would like and all that though.

Edit : I updated the code, so the username, host, and password can easily be set pragmatically. It then loops through an array of commands, checking the return with the ability to execute another command or continue on.

Here's the code with a few extra comments (hopefully helpful)

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import java.io.InputStream;
import java.util.Scanner;
import java.util.Properties;

public class cmdExec
{
  public static void main(String[] arg)
  {
    try
    {
      JSch jsch = new JSch();

      String user = "<username>";
      String host = "<host>";
      String paswrd = "<password>";

      Session session = jsch.getSession(user, host, 22);

      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");

      session.setPassword(paswrd);

      session.setConfig(config);
      session.connect();

      // build an array of commands to run
      String[] cmds = {"user | wc -l", "ps -ef | wc -l"};

      for(int cnt = 0; cnt < cmds.length; cnt++)
      {
        String command = cmds[cnt];

        Channel channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);

        channel.setInputStream(null);

        ((ChannelExec)channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];

        while (true){

            while (in.available()>0){
              int i = in.read(tmp, 0, 1024);
              if (i < 0)
              {
                break;
              }
              // grab the return, hopefully a number
              String strRet = new String(tmp, 0, i);
              // trim whitespace and convert to int
              int ret = Integer.parseInt(strRet.trim());

              if ( ret != 1 )
              {
                System.out.println("Do something else, the return wasn't one.");
              }
              else
              {
                System.out.println("Return was 1. Continuing on...");
              }
            }
            if(channel.isClosed()){
              if(in.available()>0) continue;
              //System.out.println("exit-status: "+channel.getExitStatus());
              break;
            }
            try
            {
              Thread.sleep(1000);
            }
            catch (Exception ee)
            {
              // Do something with the exception
            }  
        }
        channel.disconnect();

      }
    }
    catch(Exception e){
      System.out.println(e);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM