如何在Java sudo的权限执行bash命令? [英] How to execute bash command with sudo privileges in Java?

查看:165
本文介绍了如何在Java sudo的权限执行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();
        }
    }
}

但我想让这样的事情:

But I want to make something like this:

Process pb = new ProcessBuilder("sudo", "gedit").start();

如何通过超级用户口令打坏?

How to pass superuser password to bash?

(gksudo,gedit的)不会做的伎俩,因为它是因为Ubuntu的13.04删除,我需要在默认情况下的命令可用来做到这一点。

("gksudo", "gedit") will not do the trick, because it was deleted since Ubuntu 13.04 and I need to do this with available by default commands.

修改

gksudo回来到Ubuntu 13.04的最后一次更新。

gksudo came back to Ubuntu 13.04 with the last update.

推荐答案

我觉得你可以用这一点,但我有点犹豫张贴。所以,我只想说:

I think you can use this, but I'm a bit hesitant to post it. So I'll just say:

您自担风险,使用此不推荐,不告我,等...

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

这篇关于如何在Java sudo的权限执行bash命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆