Kevin D.
Kevin D.

Reputation: 1510

Creating a Shell Script to execute a Jar (which executes a sudo command)

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

Upvotes: 1

Views: 1077

Answers (2)

Kevin D.
Kevin D.

Reputation: 1510

Really sorry; I just added -c

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

And now it works. Thanks everyone.

Upvotes: 0

mnuss
mnuss

Reputation: 104

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.

Upvotes: 2

Related Questions