【发布时间】:2016-08-18 02:29:51
【问题描述】:
当以非特权用户身份运行Files.walk(Paths.get("/var/")).count() 时,执行可能会引发异常,因为/var/ 中存在需要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 /。哎呀。 -
应用可以弹出一个对话框,要求用户输入sudo/root密码。许多本机应用程序已经具有此功能。例如。 Gnome 软件、磁盘工具等。OOPS。 ;-)
-
正确的问题是“我如何忽略我无法访问的位置”。
-
诚实并要求对您的应用进行 sudo 执行。所有 linux 用户都会喜欢这种方法
标签: java root nio file-permissions