从Java运行多个cmd命令

时间:2018-07-12 06:34:14

标签: java cmd

我想一个接一个地从Java代码成功运行多个cmd命令。

我想使用一个创建ssh连接的命令行应用程序,并且想要像在正常的命令提示符窗口中那样成功地运行多个命令,而无需实际关闭会话。我发现有关从Java运行cmd命令的大多数答案都涉及运行单个命令然后停止。喜欢这个问题的答案:

Run cmd commands through java

我需要将命令输出重定向到控制台,并从控制台获取新命令作为输入。有点像使用Java代码模拟cmd窗口。然后根据需要结束cmd会话,并继续执行该程序的其余部分。

编辑:

我正在尝试运行名为Putty的{​​{1}}的命令行实现。用作

plink

in cmd,然后在cmd上模拟主机的linux终端。之后,直接在命令提示符下运行所有​​常见的linux命令,例如plink -ssh <hostname> -P <port> -l <username> -pw <password>。因此,我想在不关闭我的Java代码的模拟命令提示符的情况下进行仿真。

2 个答案:

答案 0 :(得分:0)

here是如何运行外部命令的答案。然后,您可以将重定向stdin重定向到任何已启动进程或当前进程的stdout,看看here。这样,您可以成功链接多个进程。

从先前提到的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);
   }
}

答案 1 :(得分:0)

我有一个要求在Linux机器上运行命令并将输出存储在日志文件中,以便用户可以轻松地验证它。代码段发布如下:

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