【问题标题】:Command is Not Interpreting in Java [closed]命令不是在 Java 中解释 [关闭]
【发布时间】:2021-04-06 18:56:24
【问题描述】:

我有这个块;

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("bash -c \"mkdir .typo && mkdir .typo/lib && mkdir src/ && mkdir bin/ && ln -sFf .typo/lib lib && mkdir .typo/runtime && touch src/main.typo && echo \"@include !main\n\ndef main(str[255] args) {\n    std:out(\"Hello, world!\");\n\n    return 0;\n}\n\" >> src/main.typo\"");

try {
    process.waitFor();
} catch (InterruptedException interruptedException) {
    System.exit(130);
}

当我执行它时,什么也没有发生。它有时会发生,但大多数情况下它不起作用。我还检查了文件系统,也没有什么不同。

(InterruptedException 使用import java.lang.InterruptedException 导入。)

我试过了,错误是;

.typo: -c: line 0: unexpected EOF while looking for matching `"'
.typo: -c: line 1: syntax error: unexpected end of file

【问题讨论】:

  • 什么都没有发生?没有创建目录?抛出异常?请准确解释发生了什么。
  • 是的,没有创建目录,也没有抛出异常。
  • -p 是干什么用的?
  • 乍一看,这可能是一个逃避问题。 @import 前面的 " 正在结束命令。
  • 我试过 mkdir -p 没有任何改变。

标签: java shell process runtime


【解决方案1】:

根据OWASP,我这样做是为了帮助提高命令的可读性并检索它们的输出(一旦执行)。

public class SafeShellExecution {

    
    public String Execute(String[] command) {
        
        StringBuilder strAppend = new StringBuilder();
        
        try {
                String line;
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = in.readLine()) != null) {
                    strAppend.append(line);
                }
                in.close();
        } catch (IOException ex) {
            Logging.LogException(ex);
        }
        
        return strAppend.toString();
    }

}

然后干净利落地定义命令:

    public static final String[] GetIPAddress = {
        "/bin/sh",
        "-c",
        "ifconfig | grep -v '127.0.0.' | grep -i 'inet ' | awk {' print $2 '} | paste -sd ','"
    };

然后执行:

SafeShellExecution.Execute(GetIPAddress);

【讨论】:

  • 让我试试看。看起来很好用。
  • 我试过了......没有任何改变。
  • 哦,等等,我在数组的开头添加了/usr/bin/bash-c,它起作用了!谢谢。
【解决方案2】:

您需要查看 stderr 输出以诊断您的命令在做什么:

添加:

        InputStream is = process.getErrorStream();
        System.out.println(IOUtils.toString(is));

在您创建流程之后。

IOUtils 来自:

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.8.0</version>
        </dependency>

当前输出为:

.typo: -c: line 0: unexpected EOF while looking for matching `"'
.typo: -c: line 1: syntax error: unexpected end of file

【讨论】:

  • 谢谢,我不(不能:P)使用 Maven,所以我按源导入包,并且我已经将 Apache Commons 导入到项目中。无论如何,我用\\\" 替换了\",所以现在它也是BaSH 中的\"
  • 希望这将有助于解决未来的任何问题。
  • 是的,我相信它会有所帮助。谢谢!顺便说一句,很抱歉,由于我的声望点,我无法投票。
  • @maDeveloper Java 将在您编写命令时执行该命令。您首先需要有一个有效的 bash 命令,然后在命令行上正确地转义它(bash 样式)(在那里尝试)。然后将其移植到 Java 并在那里再次转义(Java 风格)。
  • 哦,好的,再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 2017-07-13
  • 1970-01-01
  • 2011-03-31
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多