使用JSch的特定命令输出来触发下一个命令

时间:2016-04-20 15:35:10

标签: java ssh jsch

使用以下代码:

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();
 }  

对于这种代码,是否可能:

  1. 获取分别在控制台上触发的每个命令的输出。
  2. 根据以前的输出使用控制语句。
  3. 例如:如果我使用

    ls | wc -l
    

    输出将是固定数字,因为root中的目录不会更改。使用此编号使用if / else条件处理步骤a或b。

1 个答案:

答案 0 :(得分:0)

我之前写过这篇文章,但是我的设置与你如何设置有点不同。它会抓住你想要的回报以及所有这些。

编辑:我更新了代码,因此可以轻松地以实用方式设置用户名,主机和密码。然后循环执行一系列命令,检查返回是否能够执行另一个命令或继续执行。

这里的代码带有一些额外的评论(希望有帮助)

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);
    }
  }
}