当作为非特权用户运行Files.walk(Paths.get("/var/")).count()
时,执行可能会引发异常,因为/var/
内需要遍历root权限的文件夹。有没有办法让Java应用程序获得root权限?
我不寻找一种方式作为root用户运行bash命令(例如sudo find /var
),使用Process
等
我只是想确保Files.walk(Paths.get("/var/")).count()
不会引发AccessDeniedException
:
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0
at sun.reflect.NativeMethodAccessorImpl.invoke
at sun.reflect.DelegatingMethodAccessorImpl.invoke
at java.lang.reflect.Method.invoke
at org.springframework.boot.devtools.restart.RestartLauncher.run
Caused by: java.io.UncheckedIOException: java.nio.file.AccessDeniedException: /var/cache/httpd
at java.nio.file.FileTreeIterator.fetchNextIfNeeded
at java.nio.file.FileTreeIterator.hasNext
at java.util.Iterator.forEachRemaining
at java.util.Spliterators$IteratorSpliterator.forEachRemaining
at java.util.stream.AbstractPipeline.copyInto
at java.util.stream.AbstractPipeline.wrapAndCopyInto
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential
at java.util.stream.AbstractPipeline.evaluate
at java.util.stream.LongPipeline.reduce
at java.util.stream.LongPipeline.sum
at java.util.stream.ReferencePipeline.count
at com.example.DemoApplication.main
... 5 more
Caused by: java.nio.file.AccessDeniedException: /var/cache/httpd
at sun.nio.fs.UnixException.translateToIOException
at sun.nio.fs.UnixException.rethrowAsIOException
at sun.nio.fs.UnixException.rethrowAsIOException
at sun.nio.fs.UnixFileSystemProvider.newDirectoryStream
at java.nio.file.Files.newDirectoryStream
at java.nio.file.FileTreeWalker.visit
at java.nio.file.FileTreeWalker.next
at java.nio.file.FileTreeIterator.fetchNextIfNeeded
这只是一个例子。使用filter(...)
可以解决例外问题。但是这个例子也可以扩展到其他用例。
简而言之,CLI,JavaFX等应用程序可以通过诸如java -jar app.jar
等方法从命令行执行后获得root权限吗?
如果有可能,那么这将是一个主要的安全问题...想象一下,应用程序获得root权限并执行“rm -rf /”。哎呀。 – Tunaki
该应用可以弹出一个对话框并要求用户输入sudo/root密码。许多本机应用程序已具备此功能。例如。 Gnome软件,磁盘工具等。 ;-) – Behrang
我认为一般的方法是获取admin/root登录信息,然后产生一个与该用户分开的进程,并让该独立进程完成工作。您可能必须在每个平台上以不同方式执行此操作。我不知道是否有一个跨平台的框架可以为你处理这个问题(正如你可能知道的那样,要求其中一个将会是OT)。例如,请参阅[这里](http://stackoverflow.com/q/4662574/1076640)的Windows答案。 – yshavit