2012-07-02 152 views
1

所以我编写了一个Java程序来更改机器的IP。创建Shell脚本来执行Jar(执行sudo命令)

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

像你描述如果你正在运行的JAR,应用程序就已经具有超级用户权限,所以你根本不需要在应用程序中运行sudo。

+0

谢谢,我更新了问题 –

0

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

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

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