0

I want to automatically change the ip address of an Ubuntu 12.04 PC by a program fires at startup. For some certain reasons, I want to code it in Java.

Exactly the solution is written here:

Java - Execute a .SH file

But it does not work in my case. I could not manage to find why,essentially my case is a special case of so called thread, I try to run a sudo-command in linux with

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();
    }
}

I call this executeCommandLine() function from another function as follows:

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);
}
Community
  • 1
  • 1
fercis
  • 611
  • 2
  • 12
  • 26
  • 1
    do you receive any error or what is not working? – Danny. May 08 '14 at 12:26
  • No, I did not, but I receive the following output, and when I check the ip address, it is not configured: /bin/echo mypass | sudo -S /sbin/ifconfig usb0 192.168.0.99 mypass | sudo -S /sbin/ifconfig usb0 192.168.0.99 Especially, it seems like the system echoes the part starting from "mypass". However when I run the line from the terminal, the ip is changed – fercis May 08 '14 at 12:38
  • Please add that code which calls `executeCommandLine()` to your question, including the code which sets up the actual command that you're trying to run. Also, please describe exactly what happens when `executeCommandLine()` runs. Is there an error message? – Kenster May 08 '14 at 14:23
  • @Kenster it is allready there? changeIpAdress(...) calls executeCommandLine(strCommandLine). It seems that the code is working, but the command is not executed (Maybe I didn't understand it correctly, quite hard to mention what the questionar whants..) I'm not a linux expert, but maybe remove the /bin/echo/ ? – Danny. May 09 '14 at 07:25
  • Sorry about that, I don't know what I was thinking. – Kenster May 09 '14 at 11:25

0 Answers0