Java执行Shell脚本并传递环境变量

Java执行Shell脚本并传递环境变量

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Executor implements Runnable {
    private String shell = "";
    Map<String, String> envp = new HashMap<>();

    public Executor(String shell) {
        this.shell = shell;
    }

    public Executor(String shell, Map<String, String> envp) {
        this.shell = shell;
        this.envp = envp;
    }

    @Override
    public void run() {
        String[] commands = new String[]{"/bin/bash", "-c", shell};
        String[] env = buildEnv();
        try {
            Process process = Runtime.getRuntime().exec(commands, env);
            process.waitFor(120, TimeUnit.SECONDS);
            readOut(process.getInputStream(), System.out);
            readOut(process.getErrorStream(), System.err);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void readOut(InputStream inputStream, PrintStream out) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            ;
            String line = null;
            while ((line = reader.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String[] buildEnv() {
        Map<String, String> systemEnv = new HashMap<>(System.getenv());
        systemEnv.putAll(envp);
        return systemEnv.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).distinct().toArray(
                String[]::new);
    }
}

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        if (args.length == 0) {
            System.exit(1);
        }
        Properties properties = new Properties();
        if (args.length > 1) {
            try {
                properties.load(Files.newInputStream(Paths.get(args[1])));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Map<String, String> env = new HashMap<>();
        properties.forEach((key, val) -> env.put(key.toString(), val.toString()));
        Executor executor = new Executor(args[0], env);
        Thread thread = new Thread(executor);
        thread.start();
        thread.join();
    }
}

posted @ 2024-07-19 23:26  chmodke  阅读(29)  评论(0)    收藏  举报