1

so I wrote a Java program to change the IP of a machine.

public static void main(String[] args) {
    superUserChangeIp(args);
}

public static void superUserChangeIp(String[] args) {
    try {

        String ethInterface = args[0].toString().trim();
        String ip = args[1].toString().trim();

        System.out.println(ethInterface + " " + ip);

        String[] command = {
                "/bin/sh",
                "ifconfig " + ethInterface + " " + ip };

        Process child = Runtime.getRuntime().exec(command);

        changeNetworkInterface(ethInterface, ip);

        readOutput(child);

        child.destroy();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

I made a simple sh script :

#!/bin/sh
sudo java -jar changeip.jar $1 $2

and I'm getting : /bin/sh: 0: Can't open sudo ifconfig eth0 192.168.217.128 trying to run sh ipconfig.sh eth0 192.168.217.128

Anyone can point me to the right direction?

Note: the method changeNetworkInterface(ethInterface, ip); simply updates the settings found in /etc/network/interfaces, code follows :

protected static void changeNetworkInterface(String ethInterface, String ip) throws IOException {
    String oldInterface = File.readFile(NETWORK_INTERFACES_PATH);
    StringBuilder builder = new StringBuilder();
    Scanner reader = new Scanner(oldInterface);

    boolean startReplacing = false;

    while (reader.hasNextLine()) {
        String currentLine = reader.nextLine();

        if (currentLine.contains("iface " + ethInterface)) {
            System.out.println("Found interface!");
            startReplacing = true;
        }

        if (startReplacing && currentLine.contains("address")) {
            System.out.println("Found IP!");
            currentLine = "address " + ip;
            startReplacing = false;
        }

        builder.append(currentLine);
        builder.append("\n");
    }

    System.out.println(builder.toString());

    File.writeToFile(NETWORK_INTERFACES_PATH, builder.toString());
}

2 Answers 2

2

If you're running the JAR as you described, the application will already have superuser privileges, so you don't need to run sudo inside the app at all.

Sign up to request clarification or add additional context in comments.

Comments

0

Really sorry; I just added -c

String[] command = {
                "/bin/sh",
                "-c", // <--- this bugger right here
                "ifconfig " + ethInterface + " " + ip };

And now it works. Thanks everyone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.