gpt4 book ai didi

java - 如何使用 Java 运行存储在 String 变量中的 shell 脚本?

转载 作者:行者123 更新时间:2023-11-30 10:57:43 24 4
gpt4 key购买 nike

我需要在 Java 中执行一个 shell 脚本。我的 shell 脚本不在文件中,它实际上存储在一个 String 变量中。我正在从其他应用程序获取我的 shell 脚本详细信息。

我知道如何在 Java 中执行不同的命令,如下所示:

public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/david/pk.txt");
System.out.println(commands);

//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/david"));
pb.redirectErrorStream(true);
Process process = pb.start();

//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}

//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}

//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}

在我的例子中,我将在一个 json 字符串变量中包含脚本信息,我从中提取脚本的内容:

{"script":"#!/bin/bash\n\necho \"Hello World\"\n"}

下面是我的代码,我在其中从上面的 json 中提取脚本内容,现在我不确定如何执行该脚本并将一些参数传递给它。现在,我可以传递任何简单的字符串参数:

String script = extractScriptValue(path, "script"); // this will give back actual shell script

// now how can I execute this shell script using the same above program?
// Also how I can pass some parameters as well to any shell script?

执行上面的脚本后,应该会打印出Hello World。

最佳答案

您需要使用 shell 启动一个 Process,然后将您的脚本发送到它的输入流。以下只是概念验证,您需要更改一些内容(例如使用 ProcessBuilder 创建流程):

public static void main(String[] args) throws IOException, InterruptedException {

// this is your script in a string
String script = "#!/bin/bash\n\necho \"Hello World\"\n echo $val";

List<String> commandList = new ArrayList<>();
commandList.add("/bin/bash");

ProcessBuilder builder = new ProcessBuilder(commandList);
builder.environment().put("val", "42");
builder.redirectErrorStream(true);
Process shell = builder.start();

// Send your script to the input of the shell, something
// like doing cat script.sh | bash in the terminal
try(OutputStream commands = shell.getOutputStream()) {
commands.write(script.getBytes());
}

// read the outcome
try(BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}

// check the exit code
int exitCode = shell.waitFor();
System.out.println("EXIT CODE: " + exitCode);
}

关于java - 如何使用 Java 运行存储在 String 变量中的 shell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32492115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com