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

后端 未结 3 575
野的像风
野的像风 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条回答
  •  -上瘾入骨i
    2020-12-15 07:41

    If what you want is actually skipping the paths where you have no access, you have two approaches:

    Streams

    In the answer to this question it is explained how to obtain the stream of all files of a subtree you can access.

    But this example can be expanded to other use cases too.

    FileVisitor

    Using a FileVisitor adds a lot of code, but grants you much more flexibility when walking directory trees. To solve the same problem you can replace Files.walk() with:

    Files.walkFileTree(Path start, FileVisitor visitor);
    

    extending SimpleFileVisitor (to count the files) and overriding some methods.

    You can:

    1. Override the visitFileFailed method, to handle the case you cannot access a file for some reasons; (Lukasz_Plawny's advice)
    2. (optional) Override the preVisitDirectory method, checking for permissions before accessing the directory: if you can't access it, you can simply skip its subtree (keep in mind that you may be able to access a directory, but not all its files);

    e.g. 1

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        // you can log the exception 'exc'
        return FileVisitResult.SKIP_SUBTREE;
    }
    

    e.g. 2

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
    
        if(!Files.isReadable(dir))
            return FileVisitResult.SKIP_SUBTREE;
    
        return FileVisitResult.CONTINUE;
    
    }
    

    FileVisitor docs

    FileVisitor tutorial

    Hope it helps.

提交回复
热议问题