【问题标题】:Run multiple cmd commands from java从java运行多个cmd命令
【发布时间】:2018-07-12 06:34:14
【问题描述】:

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

我想使用这个创建 ssh 连接的命令行应用程序,并且我想像在普通命令提示符窗口中一样连续运行多个命令,而无需实际关闭会话。我发现的关于从 java 运行 cmd 命令的大多数答案都谈到了运行单个命令然后停止。喜欢这个问题的答案:

Run cmd commands through java

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

编辑:

我正在尝试运行名为plink 的Putty 的命令行实现。它被用作

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

在 cmd 中,然后在 cmd 上模拟主机的 linux 终端。之后,您可以直接在命令提示符中运行所有常用的 linux 命令,例如 ls。所以我想在不关闭我的 java 代码的所谓模拟命令提示符的情况下模拟它。

【问题讨论】:

  • 实际上,在您链接到的帖子中接受的答案中正在运行两个命令。 cd <path> && dir.
  • @notjustme 但他们在一行中完成并关闭会话。当我没有预定义的命令数量时,我想学习如何在旅途中执行此操作,因为我将它们作为输入。
  • 你为什么不直接使用bash?
  • 至于非交互式plink使用,请查阅plink -m。

标签: java cmd


【解决方案1】:

如何运行外部命令的答案是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);
   }
}

【讨论】:

  • 但是如何在同一个 cmd 会话中连续运行所有命令呢?
  • 你会像这样启动多个进程:Process process = Runtime.getRuntime().exec ("your/external/program");,然后你会将它的 inputStream 重定向到另一个已启动进程的 outputStream,依此类推。
【解决方案2】:

我有一个要求是在 linux 机器上运行命令并将输出存储在日志文件中,以便用户可以轻松地对其进行验证。代码 sn-p 贴在下面:

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

【讨论】:

  • 我最初也曾尝试使用 jsch 创建一个应用程序,但由于服务器上的安全验证,我必须使用 putty。这就是为什么我需要在 cmd 中使用 plink 并尝试。
猜你喜欢
  • 2013-04-30
  • 2021-05-03
  • 2013-06-08
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多