创建Shell脚本以执行Jar(执行sudo命令)

时间:2012-07-02 02:42:18

标签: java linux shell ubuntu

所以我写了一个Java程序来改变一台机器的IP。

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

我做了一个简单的sh脚本:

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

我得到:/bin/sh: 0: Can't open sudo ifconfig eth0 192.168.217.128试图运行sh ipconfig.sh eth0 192.168.217.128

任何人都可以指出我正确的方向吗?

注意:方法changeNetworkInterface(ethInterface, ip);只是更新/etc/network/interfaces中的设置,代码如下:

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 个答案:

答案 0 :(得分:2)

如果你正如你所描述的那样运行JAR,那么应用程序将具有超级用户权限,因此你根本不需要在应用程序中运行sudo。

答案 1 :(得分:0)

真的很抱歉;我刚刚添加了-c

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

现在它有效。谢谢大家。