开发者

Check if a user is root in a java application

How can i verify if a user is root in a java application?

开发者_运维知识库

Thanks


Process p = Runtime.getRuntime().exec("id -u")

Keep in mind that the "root" user on a system may not be called root (although it's rare to change it), and it's also possible to alias it to another username. If the current user is root-like, the output will be 0.


Easy. Just use

System.getProperty("user.name")


run a native command? like whoami


You can call

  Process p = Runtime.getRuntime.exec("whoami")

method. Then you can process p's stdout to read output of command.


Check this: get login username in java.


The best way is to run

 Process p = Runtime.getRuntime.exec("groups `whoaim`"); 

and try to parse string to get group call root. Your JVM process could be run by user not call root but i.e. moderator but this user could be in root group and you have root privileges.


String userName = System.getProperty("user.name");
Process p = Runtime.getRuntime().exec("groups " + userName);
String output = read(p.getInputStream());
String error = read(p.getErrorStream());

And here is a read function:

public static String read(InputStream input) throws IOException {
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
        return buffer.lines().collect(Collectors.joining("\n"));
    }
}

Just "another" modified solution.


Here is a complete Utility class with a working method

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;


public interface U {

public static final Logger l = LogManager.getLogger(U.class.getName());

 public static boolean isRoot() {
    try {
        Process p = Runtime.getRuntime().exec("id -u");
        StringWriter sw = new StringWriter();
        InputStreamReader isw = new InputStreamReader(p.getInputStream());
        isw.transferTo(sw);
        String output = sw.toString();
        l.trace("id -u output = [{}]", output);
        return output.startsWith("0");
    } catch (IOException e) {
        l.error("", e);
    }
    return false;
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜