java - 如何通过java将参数传递给shell命令?

标签 java shell unix exec

我对这种 java 与 Unix 的集成很陌生。

我想做的是

    String command="passwd";
    Runtime rt=Runtime.getRuntime();
    try {
        Process pc=rt.exec(command);
        try {
            pc.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        BufferedReader buf = new BufferedReader(new InputStreamReader(pc.getInputStream()));

        String line = "";

        while ((line=buf.readLine())!=null) {

        System.out.println(line);

        }
        BufferedReader buf1 = new BufferedReader(new InputStreamReader(pc.getErrorStream()));

        String line1 = "";
        while ((line1=buf1.readLine())!=null) {

            System.out.println("Error--"+line1);

            }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        System.out.println("IOException---"+e1.getMessage());
    }

现在,当我尝试传递“passwd”命令时,Unix 环境进入挂起模式。

我想知道如何使用 java 代码将旧密码、新密码和确认新密码传递给 shell。

最佳答案

您需要使用混淆名称 Process.getOutputStream() 来传递它.来自文档:

Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object

请注意,您需要同时 捕获进程 stdout/err 以避免阻塞。参见 this answer了解更多详情。

关于java - 如何通过java将参数传递给shell命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12836166/

相关文章:

c++ - 以管理员身份运行命令行进程 Qt

c - 如何打开和打印目录中的所有文件

java - 自定义gradle插件+访问方法的返回值?

java - 在 java 代码中创建 postgresql 表

java - 关于字符串操作的问题

shell - $?VAR 在 csh 中是什么意思?

java - Netbeans GUI 和处理 "main"内的线程

linux - 无法在 Unix 中捕获 SIGQUIT 信号

unix - 复制文件后Wget不会退出

linux - 如何使用 sed 或 awk 在单独的文件中使用模式 grep 行