0

I want to run multiple cmd commands succesively from java code one after the other.

I want to use this one command line application which creates ssh connection and I want to run multiple commands succesively like in a normal command prompt window without actually closing the session. Most answers I found about running cmd command from java talked about running a single command and then stopping. Like the answer in this question:

Run cmd commands through java

I need to redirect the output of my commands to the console and also get the new commands as inputs from the console. Sort of like emulating a cmd window using java code. And then end the cmd session as necessary and continue with the rest of the program.

EDIT:

I am trying to run a command line implementation of Putty called plink. It is used as

plink -ssh <hostname> -P <port> -l <username> -pw <password>

in cmd and then the linux terminal of the host is emulated on the cmd. After that you run all the usual linux commands like ls straight into the command prompt. So I want to emulate that without closing the supposedly emulated command prompt of my java code.

2 Answers2

0

Answer to how to run external commands is here. Then you can use redirect stdin to stdout of any started process or current process, take a look here. This way you can link multiple processes in succesion.

The answer borrowed from previously mentioned answer:

public static void pipeStream(InputStream input, OutputStream output)
   throws IOException
{
   byte buffer[] = new byte[1024];
   int numRead = 0;

   do
   {
      numRead = input.read(buffer);
      output.write(buffer, 0, numRead);
   } while (input.available() > 0);

   output.flush();
}

public static void main(String[] argv)
{
   FileInputStream fileIn = null;
   FileOutputStream fileOut = null;

   OutputStream procIn = null;
   InputStream procOut = null;

   try
   {
      fileIn = new FileInputStream("test.txt");
      fileOut = new FileOutputStream("testOut.txt");

      Process process = Runtime.getRuntime().exec ("/bin/cat");
      procIn = process.getOutputStream();
      procOut = process.getInputStream();

      pipeStream(fileIn, procIn);
      pipeStream(procOut, fileOut);
   }
   catch (IOException ioe)
   {
      System.out.println(ioe);
   }
}
AndrejH
  • 2,028
  • 1
  • 11
  • 23
  • But how to run all the commands successively in the same cmd session? – Pratik Mayekar Jul 12 '18 at 06:45
  • You would get start multiple processes like this: `Process process = Runtime.getRuntime().exec ("your/external/program");`, then you would redirect it's `inputStream` to an `outputStream` of another started process and so on. – AndrejH Jul 12 '18 at 06:50
0

I had one requirement to run the command on linux machine and store the output in the log file so that it could easily be verified by the user. code snippet posted below:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Connection
{
 public static void setConnection(String hostName)
{
    String host = hostName;
    Properties prop = new Properties();
    InputStream input = null;

    try
    {

        input = new FileInputStream("./config/finalvalidation.properties");
        Log.log("Validation of the Host Started: " + host);

        prop.load(input);
        String user = prop.getProperty("username");
        Log.log("Username : " + user);

        String password = prop.getProperty("password");
        Log.log("Password in property file is: " + password);

        String privateKey = prop.getProperty("ppkfile");

        Log.log("Password: " + password);
        Log.log("ppkfile: " + privateKey);

        String command1 = prop.getProperty("command");
            Log.log("command: " + command1);

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);

        if (password != null && !password.isEmpty() && (privateKey == null || 
   privateKey.isEmpty()))
        {
            session.setPassword(password);
            Log.log("Password identity added ");
        }
        else if (privateKey != null && !privateKey.isEmpty() && (password == null || 
password.isEmpty()))
        {
            jsch.addIdentity(privateKey);
            Log.log("PPK identity added ");
        }
        else
        {
            Log.log("Please correct Password or PPK file placement in 
 finalvalidation.properties");
        }

        session.setConfig(config);
        session.setPassword(password);
        session.connect();
        Log.log("Connected");

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command1);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream inp = channel.getInputStream();
        channel.connect();
        byte[] tmp = new byte[1024];
        while (true)
        {
            while (inp.available() > 0)
            {
                int i = inp.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                Log.log(new String(tmp, 0, i));
                System.out.println(tmp.toString());
            }
            if (channel.isClosed())
            {
                Log.log("exit-status: " + channel.getExitStatus());

                break;
            }
            try
            {
                Thread.sleep(500);
            }
            catch (Exception ee)
            {

            }
        }
        channel.disconnect();
        session.disconnect();
        Log.log("Validation of the host completed " + host);
        Log.log("------------------------------DONE------------------------");
    }
    catch (Exception e)
    {
        e.printStackTrace();

    }
    finally
    {
        if (input != null)
        {
            try
            {
                input.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

}

command=ls -lrt  /appl/websphere.ear |  ls -lrt /appl/prd*/ProcMgrA* | cat /appl/prd*/EF_info.txt
  • I also had initially tried to create an app with jsch but due to security verification on the servers I have to use putty. Which is why I need to use plink in cmd and try. – Pratik Mayekar Jul 12 '18 at 07:51