如何从java执行linux终端命令?

时间:2014-05-08 12:23:18

标签: java linux sh

我想在程序启动时自动更改Ubuntu 12.04 PC的IP地址。出于某些原因,我想用Java编写代码。

解决方案正好写在这里:

Java - Execute a .SH file

但它在我的情况下不起作用。我无法找到原因,基本上我的情况是所谓的线程的特殊情况,我尝试在linux中运行sudo-command

public static void executeCommandLine(String strCommand){
    Runtime rt = Runtime.getRuntime();
    try {
        Process p = rt.exec(strCommand);
        if(p==null){
            System.out.println("Error in process");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = null;
         try {
            while ((line = reader.readLine()) != null)
             {
                System.out.println(line);
             }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我从另一个函数调用此executeCommandLine()函数,如下所示:

public static void changeIpAddress(String strIpAddress, String strRootPassword, String strEthDevice){
    String strCommandLine = "";

    if(PLATFORM == PLATFORM_LINUX){
        strCommandLine =  "/bin/echo " + strRootPassword +  "| sudo -S /sbin/ifconfig " + strEthDevice + " " + strIpAddress;
    }else if(PLATFORM == PLATFORM_WINDOWS){
        // TODO: Write for Windows
    }else{
        System.out.println("OS not supported");
    }

    System.out.println("Executed command:");
    System.out.println(strCommandLine);

    executeCommandLine(strCommandLine);
}

0 个答案:

没有答案