0

可能重复:
使用 java 执行带有“sudo”的 linux shell 命令,而无需输入所需的密码

我想通过java程序在linux上执行sudo命令,但它要求输入密码。但我想在没有密码的情况下运行 prog,请告诉我。我的编是

public class JavaCommandProg {
    public static void main(String args[]) throws IOException, InterruptedException {
        String command="sudo cat /etc/sudoers";
        Process myProcess =null;
        try {
            Runtime runtime=Runtime.getRuntime();
            File file=new File("/home/users/admin/temp");
            myProcess = runtime.exec(command,null,file);
            myProcess.waitFor();
            InputStreamReader myIStreamReader = new InputStreamReader(myProcess.getInputStream());
            BufferedReader br=new BufferedReader(myIStreamReader);
            String line;
            while((line=br.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException anIOException) {
            System.out.println(anIOException);
        }
    }
}

Compling like: javac JavaCommandProg.java
and          : java JavaCommandProg
4

2 回答 2

1

使用 sudo 授予用户权限。看看这里:http ://www.ducea.com/2006/06/18/linux-tips-password-usage-in-sudo-passwd-nopasswd/

例如:

/etc/sudoers
admin    ALL = NOPASSWD: ALL
于 2012-05-24T07:16:04.737 回答
0

If you can get it to run that would mean a security flaw.

Said so...

  1. Grant your user permissions (become sudoer)
  2. Invoke your java program with sudo

    $ sudo java JavaCommandProg

This will prompt you for introducing sudo password when running jvm and then you can invoke sudo from inside your Java program.

于 2012-05-24T07:20:39.167 回答