Is there a way for a Java app to gain root permissions?

后端 未结 3 584
野的像风
野的像风 2020-12-15 07:02

When running Files.walk(Paths.get(\"/var/\")).count() as an unprivileged user, the execution might throw an exception as there are folders inside /var/

3条回答
  •  感动是毒
    2020-12-15 07:59

    Just a few completely untested ideas:

    1) Run your app with root priviledges to begin with:

    sudo java -jar myapp.jar

    2) Let your app start a launcher-class that requests root permissions and then continues running the rest of your app:

    java -jar myapp.jar

    This in turn does execute a shell command, but only an xterm that prompts for root password, and then continues to run a java program with root permissions:

    xterm -e "sudo sh -c 'java -jar /tmp/myrootapp.jar'"

    or perhaps use something nicer-looking using gksudo. Mind the ' and ".

    Maybe the myapp.jar extracts itself into a temporary directory. myapp.jar contains myrootapp.jar and thus it can launch it as described above. /tmp should of course be retrieved from within java, and preferably be a directory with a random name that only the user running myapp.jar has access to in order to prevent myrootapp.jar injection.

    Cross-platform

    You mentioned /var/ yourself, so I assumed you were on some sort of Linux. If this is supposed to work cross-platform, e.g. on Macintosh or Microsoft Windows too, you need to do some sort of system identification first. Then you can apply StrategyPattern in code to handle the various ways of letting myrootapp.jar obtain root or administrator permissions.

提交回复
热议问题