【问题标题】:How to input the password while executing cmd through java通过java执行cmd时如何输入密码
【发布时间】:2015-01-22 06:21:19
【问题描述】:

我想编写一个 java 程序来检索在不同服务器上运行的所有服务的状态(大约 20 个)。为此,我使用的是 SC 命令,我可以使用 java 程序来做到这一点。但是现在我陷入了一种情况,我想通过使用 RUNAS 以其他用户身份运行 SC 命令,我面临的问题是,一旦第一次执行命令,我就无法输入密码.以下是我正在使用的代码:-

        String[] command = new String[3];
        command[0] = "cmd";
        command[1] = "/c";
        command[2] = "runas /noprofile /user:domain\\admin \"sc \\\\serverName queryex type= service state= all\"";

        Process p = Runtime.getRuntime().exec(command);

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = reader.readLine();

        while (line != null) {

            new PrintWriter(p.getOutputStream(),true).println("AdminPassword");

            System.out.println(line);
            line = reader.readLine();
        }

        BufferedReader stdInput = new BufferedReader(newInputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String Input;
        while ((Input = stdInput.readLine()) != null) {
            System.out.println(Input);
        }            

        String Error;
        while ((Error = stdError.readLine()) != null) {
            System.out.println(Error);
        }

但我无法打印所有服务的状态。提供密码后我不确定是否需要捕获其他流??

有什么帮助吗?

谢谢

【问题讨论】:

  • 一个安全问题可能会影响您,这里的大部分答案可能是:如果您通过命令行提供凭据,则在使用任务管理器或查看进程列表时,它们可能以纯文本形式提供类似的东西。

标签: java cmd runas


【解决方案1】:

在您的while (line != null) 循环中,您为您阅读的每一行打开一个新的 PrintWriter。您将管理员密码打印给这些 writer,但永远不要关闭或刷新它们。

试试你上面创建的PrintWriter writer,写完密码后再试试flush(),不然还在缓存中。

您还在Process的inputStream上创建了几个BufferedReader,这可能会相互干扰。

所以:只创建一个阅读器。 Process 的 inputStream、errorStream 和 outputStream 的 writer。

【讨论】:

  • 嗨,Thomos,感谢您的回复,我已将 printwriter 代码置于循环之外(之前)并进行了刷新和关闭,但结果仍然相同。
猜你喜欢
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2015-01-23
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多