Search code examples
javajavafxrootsudo

request root permissions from java to restart systemctl services


I am writing an app that changes the ip-address on Windows and Ubuntu. I need to run some commands in terminal as root, so i need to call native ubuntu (and others linux distributions) dialog, which gives root priviledge after entering root password.

How can i call this dialog? screenshot of dialog from ubuntu

Here is the command which i need to run as root from java code, maybe it can help.

ProcessBuilder builder = new ProcessBuilder("/bin/bash",
                        "-c",
                        "systemctl restart networking")
                        .redirectErrorStream(true);

Solution

  • For starters, the procedure differs between Windows and Ubuntu, so I will focus on Ubuntu. If your application is expected to run on cross-platform, you might need to do some sort of system identification first. Then you can apply StrategyPattern in code to handle the various ways of letting your application obtain root or administrator permissions

    As I understand your your end goal is to execute the command as root, in which case, there are several means to that end

    1) You can run your Java application as a root. This would mean that the Application can only be executed by a root user. This is especially advantageous because the root user may be unavailable for one reason or the other, and you can let the user deal with that issue. It should be something like this:

    sudo java -jar myapp.jar

    2) Use 'sudo' with the '-S' switch and pass the user's password to the Process stdin. This requires the user to be registered in the sudoers configuration file with permissions set to execute the command being run. This could mean that you pass the password as an argument to your application during launch.

    3) Use 'gksudo' which automatically brings up a password dialog. It also requires the user to be registered in the sudoers configuration file and, of course, that 'gksudo' is available. For this method, it would look something like this

    String[] command = {"gksudo", "systemctl restart networking"};
    Process p = Runtime.getRuntime().exec(command);