PascalV
PascalV

Reputation: 111

Checking SFTP permissions using Jsch

I'm currently implementing a SFTP client using Jsch.

For this client I need to check the permissions the logged in user has on the SFTP server in order to check if user is able to perform certain operations. Unfortunately I can't seem to find any documentation or examples in which is shown how to to this.

Thanks in advance.

Upvotes: 6

Views: 4665

Answers (2)

Zon
Zon

Reputation: 19880

Same approach in a ready method (formatted and refactored):

  private boolean accessAllowed(String path) 
    throws SftpException, JSchException {

    boolean result = false;

    ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
    SftpATTRS attrs = channel.lstat(path);

    result =
      attrs != null &&
      ((attrs.getPermissions() & 00200) != 0) &&
       attrs.getUId() != 0;

    return result;
  }

Upvotes: -1

Dmitry Trofimov
Dmitry Trofimov

Reputation: 7601

This code will do what you want:

ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
SftpATTRS attrs = channel.lstat(fileOnServer)
boolean userHasPermissionsToWriteFile = attrs != null && ((attrs.getPermissions() & 00200) != 0) && attrs.getUId() != 0; 

Where

attrs.getUId() != 0

checks that user is not root

Upvotes: 5

Related Questions