【问题标题】:Creating a Shell Script to execute a Jar (which executes a sudo command)创建一个 Shell 脚本来执行一个 Jar(它执行一个 sudo 命令)
【发布时间】:2012-07-02 11:45:15
【问题描述】:

所以我写了一个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());
}

【问题讨论】:

    标签: java linux shell ubuntu


    【解决方案1】:

    如果您按照描述运行 JAR,则应用程序已经拥有超级用户权限,因此您根本不需要在应用程序内运行 sudo。

    【讨论】:

      【解决方案2】:

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

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

      现在它可以工作了。谢谢大家。

      【讨论】:

        猜你喜欢
        • 2018-09-19
        • 1970-01-01
        • 1970-01-01
        • 2012-10-19
        • 2018-10-20
        • 1970-01-01
        • 1970-01-01
        • 2017-05-28
        • 1970-01-01
        相关资源
        最近更新 更多