【问题标题】:how to pass the arguments to the shell command through java?如何通过java将参数传递给shell命令?
【发布时间】:2012-10-01 22:00:54
【问题描述】:

我不熟悉这种 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 传递旧密码、新密码和确认新密码。

【问题讨论】:

    标签: java shell unix exec


    【解决方案1】:

    有一个名为 expect 的实用程序。如果你安装了你可以为任何事情传递参数。所以构造为字符串执行 字符串构造命令; 进程 p=Runtime.getRuntime().exec(ConstructedCommand);

    此链接值得您的需要。 http://linux.die.net/man/1/expect

    【讨论】:

      【解决方案2】:

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

      获取子进程的输出流。输出到流是 通过管道传输到由表示的进程的标准输入流中 这个进程对象

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 2020-07-02
        • 1970-01-01
        相关资源
        最近更新 更多