问题
I know there is getPermissions()
method but I don't know how to use it. How can I check using JSch, if user can read files?
回答1:
First, you should generally ask a functional question (what do you want to achive), to get an useful answer. You ask for an implementation/technical detail, hence my possibly useless technical answer:
SftpATTRS.getPermissions()
returns numerical representation of *nix permissions:
https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation
It's on its own NOT enough to determine, if the current user has permissions to read the file. In addition you have to know: who is the owner of the file (the getUId
returns owner ID, but there's no API in SFTP to map that to/from username) and what is a group of the file (the getGId
, the same).
So you can only be sure that user can read the file, when everyone have permissions to do so. What you can tell by presence of flag 0004
(read permissions for other class). But lack of the flag does not mean user cannot read the file, e.g. in case user is an owner of the file and there's flag 0400
(read permissions for owner class).
Also note that, when the remote system is not *nix (e.g. it's Windows), the getPermissions()
value is usually irrelevant anyway.
Non-trivial, but only reliable way, is to dig into JSch source code and extract new API to open file for reading. Then you can just try to open the file (you do not have to read anything actually) to tell, if user has permissions to do so.
来源:https://stackoverflow.com/questions/16686858/how-to-check-for-read-permission-using-jsch-with-sftp-protocol