如何在Java中使用sudo权限执行bash命令?

Var*_*Zon 24 java linux bash ubuntu

我正在使用ProcessBuilder来执行bash命令:

import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            Process pb = new ProcessBuilder("gedit").start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我想做这样的事情:

Process pb = new ProcessBuilder("sudo", "gedit").start();
Run Code Online (Sandbox Code Playgroud)

如何将超级用户密码传递给bash?

("gksudo", "gedit") 不会这样做,因为它已经被删除,因为Ubuntu 13.04并且我需要使用默认命令可用.

编辑

gksudo在最后一次更新时回到了Ubuntu 13.04.

Eri*_*agt 32

我想你可以使用它,但我有点犹豫要发布它.所以我只想说:

使用此风险自负,不推荐,不要起诉我等等......

public static void main(String[] args) throws IOException {

    String[] cmd = {"/bin/bash","-c","echo password| sudo -S ls"};
    Process pb = Runtime.getRuntime().exec(cmd);

    String line;
    BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
    while ((line = input.readLine()) != null) {
        System.out.println(line);
    }
    input.close();
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,现在它正在工作:)`{"/ bin/bash"," - c","echo \"password \"| sudo -S ls"};`谢谢. (3认同)
  • 该代码可以完美地工作,但不是一个好的解决方案,因为它在命令行中公开了密码,其他进程可以看到它。 (2认同)

Joi*_*ort 12

使用visudo编辑/ etc/sudoers并为您的用户授予特定脚本的NOPASSWD权限:

username ALL =(ALL)NOPASSWD:/opt/yourscript.sh

  • 或者按照armnotstrong的建议将文件添加到“/etc/sudoers.d”:/sf/answers/2946330271/ (2认同)

arm*_*ong 7

不要尝试在文件中明确写入系统密码,特别是对于具有 sudo 权限的用户,正如 @jointEffort 回答的那样,颁发的权限应该由系统管理员而不是应用程序编写者来解决。

sudo允许您将特定命令的权限授予特定用户,这已经足够了,请查看这篇文章

如果您只想附加在主文件中(大多数 Linux 发行版已经这样做),并且创建一个如下文件,则可以选择在主sudoers文件之外的单独文件中管理权限:#includedirs /etc/sudoers.d//etc/sudoersifconfig-user

 USER_NAME ALL=(ALL) NOPASSWD: /sbin/ifconfig
Run Code Online (Sandbox Code Playgroud)

另一件事,请记住编辑配置文件,以防visudo在出现语法错误时失去对系统的控制。


kat*_*to2 5

我的解决方案没有在命令行中公开密码,它只是将密码提供给进程的输出流。这是一种更灵活的解决方案,因为允许您在需要时向用户请求密码。

public static boolean runWithPrivileges() {
    InputStreamReader input;
    OutputStreamWriter output;

    try {
        //Create the process and start it.
        Process pb = new ProcessBuilder(new String[]{"/bin/bash", "-c", "/usr/bin/sudo -S /bin/cat /etc/sudoers 2>&1"}).start();
        output = new OutputStreamWriter(pb.getOutputStream());
        input = new InputStreamReader(pb.getInputStream());

        int bytes, tryies = 0;
        char buffer[] = new char[1024];
        while ((bytes = input.read(buffer, 0, 1024)) != -1) {
            if(bytes == 0)
                continue;
            //Output the data to console, for debug purposes
            String data = String.valueOf(buffer, 0, bytes);
            System.out.println(data);
            // Check for password request
            if (data.contains("[sudo] password")) {
                // Here you can request the password to user using JOPtionPane or System.console().readPassword();
                // I'm just hard coding the password, but in real it's not good.
                char password[] = new char[]{'t','e','s','t'};
                output.write(password);
                output.write('\n');
                output.flush();
                // erase password data, to avoid security issues.
                Arrays.fill(password, '\0');
                tryies++;
            }
        }

        return tryies < 3;
    } catch (IOException ex) {
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)