2

我想使用带有进程构建器的 aws s3 cli 命令从 s3 存储桶下载文件。代码如下。如果我不想对文件名进行硬编码,则会收到错误消息。谁能告诉我如何在命令中传递变量。

public static void main(String[] args) {
    ProcessBuilder processBuilder = new ProcessBuilder();
    Map<String, String> env = processBuilder.environment();
    System.out.println(env);
    String fileName = "NBN-20210623000000000001";

    // Checking if the system is windows or not
    if (System.getProperty("os.name")
            .startsWith("Windows")) {
        // processBuilder.command("cmd.exe", "/c", "echo %cd%");
        // Need to pass the cli commands to download the file based on the --profile
        processBuilder.command("cmd.exe", "/c",
                "aws s3 cp s3://npis-sam-deal-calculator/estimate/ASI000000000042/AsynchronousProcess/${fileName} src/main/resources/ --profile npis-dev-np");
    } else {
        // In pipeline the environment is on unix so need to get the profile from the
        // environment variable
        processBuilder.command("/bin/bash", "-c",
                "aws s3 cp s3://npis-sam-deal-calculator/pricelist/dcpl.csv src/test/resources/ --profile ${aws_profile}");
    }

    try {
        Process process = processBuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        int exitCode = process.waitFor();
        System.out.println("\nExited with error code : " + exitCode);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

如果你看到了,我在fileName. 但是, fileName在 Windows 的 s3 命​​令中使用我无法下载该文件。可以做些什么来解决这个问题?

4

1 回答 1

0

如果输入 (和) 未正确清理,您的方法可能会产生命令注入漏洞。谨慎使用并小心。控制这些参数的人可以在调用的 shell 上执行任意命令。与 AWS S3 交互的另一种方法是使用AWS SDK for JavafileNameaws_profile


Java 不会${fileName}用文件名替换命令字符串中的内容。您可以使用字符串连接将文件名放入命令中。fileName如果您无法绝对控制其内容,请记住进行消毒。

String fileName = "NBN-20210623000000000001";
String command = "aws s3 cp" +
        " s3://npis-sam-deal-calculator/estimate/ASI000000000042/AsynchronousProcess/" +
        fileName +
        " src/main/resources/" +
        " --profile npis-dev-np";

processBuilder.command("cmd.exe", "/c", command);

要插入环境变量,您可以像这样安全地执行此操作:

String awsProfile = System.getenv("aws_profile"); // OS independent
// sanitize awsProfile
String command = "aws s3 cp" +
        " s3://npis-sam-deal-calculator/pricelist/dcpl.csv" +
        " src/test/resources/" +
        " --profile " + awsProfile;

processBuilder.command("/bin/bash", "-c", command);
于 2021-06-24T06:49:23.553 回答