简体   繁体   中英

JSch How do I retrieve results from a series of piped commands

My COMMAND has a first part whose results are piped into a second part. When I run the code I always get returned the results of the first part, and the filter applied by the second part is apparently not executed.

So I get :

CONTAINER ID   IMAGE  COMMAND   CREATED      STATUS       PORTS   NAMES
abcdeff        a/b/1  "usr/.."  15 mins ago  Up to 2 mins         something.1.2
123abcd        a/b/2  "usr/.."  32 mins ago  exited               something.1.3
234456d        a/b/3  "usr/.."  2 days ago   exited               something.1.4

Where I want

CONTAINER
abcdeff
123abcd
234456d
public class Test {

  private static COMMAND =
  "echo \"password\" | sudo -S bash -c \"docker container ls --all | awk '{print $1}'\""

  executeExecCommand(command){
    JSch jsch = new JSch();
    Session session=jschgetSession(username, ipaddress, 22);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setConfif("PreferredAuthentications", "password");
    Channel channel = session.openChannel("exec");
    ((ChannelExec)channel).setCommand(COMMAND);
    channel.setInputStream(null);
    ((ChannelExec)channel).setErrStream(System.err);
    InputStream input = channel.getInputStream();
    InputStream error = channel.getExtInputStream();
    channel.connect();
    List<String> output = new ArrayList<>();
    List<String> errorOutput = new ArrayList<>();

    try (InputStreamReader inputReader = new InputStreamReader(input);
      BufferedReader bufferedReader = new BufferedReader(inputReader);
      InputStreamReader errorReader = new InputStreamReader(error)) {

       String line = null;
       while (true) {
         while ((line = bufferedReader.readLine() != null {
         output.add(line:
         System.out.println("line = " + line);

       etc
       etc
       }
     }
}

Is this something to do with the piped process being executed in a different shell on the target server? If so, how do I achieve my goal of returning the filtered list?

I needed to escape the $. COMMAND = "echo \\"password\\" | sudo -S bash -c \\"docker container ls --all | awk '{print \\$1}'\\"" works

Note that if I want to further develop this command to delete containers for instance, I also need to escape the backtick.

COMMAND = "echo \\"password\\" | sudo -S bash -c \\"docker container rm `docker container ls --all | awk '{print \\$1}'\\`\\""

It needs a double backslash to escape the $ and backtick. It's showing as a single backslash here

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