Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jscape sftp upload preserving file permission

I am using jscape sftp to transfer files

com.jscape.inet.sftp.Sftp

Sftp sftpSession = null;

// after the required step to connect
// through SshParameters

sftpSession.setDir(remotedirectory);
sftpSession.upload(localFile, remoteFile);

now, this code is transferring the file, that part OK. but the file permission is getting changed in remote machine (it's becoming 644).

in local machine:    
-rw-rw-r-- 1 oracle dba  356 Jun 30 03:33 file1.test
-rwxrw-r-x 1 oracle dba  462 Jun 30 03:35 file2.test

in remote machine:
-rw-r--r-- 1 oracle dba  356 Jun 30 03:49 file1.test
-rw-r--r-- 1 oracle dba  462 Jun 30 03:49 file2.test

I see the below method to change the permission of remote file,

com.jscape.inet.sftp.Sftp.setFilePermissions(java.lang.String remoteFile, int permissions)

My questions are,

  • does the com.jscape.inet.sftp.Sftp.upload method works this way only, upload the file without preserving the permission?
  • is there any way to preserve the permission, without using setFilePermissions method explicitly?
like image 267
Denim Datta Avatar asked Jun 30 '15 11:06

Denim Datta


2 Answers

Does the user and group on remote have same permissions as on local, to the directory being uploaded? You can try getting the permissions on local using getPermissions() method and setting the same to remote file.

like image 50
Gautam Jose Avatar answered Nov 05 '22 12:11

Gautam Jose


With Java 7+ you can do that; the code below of course assumes a setup similar to yours, that it POSIX compliant filesystems on both ends.

The trick is to obtain the set of POSIX file permissions on a file; this is done using:

// "fileToCopy" here is a Path; see Paths.get()
Files.getPosixFilePermissions(fileToCopy)

This will return a Set<PosixFilePermissions>, which is in fact an enum. Transforming the enum into an integer is done using the following trick:

private static int toIntPermissions(final Set<PosixFilePermission> perms)
{
    int ret = 0;
    for (final PosixFilePermission perm: PosixFilePermission.values()) {
        if (perms.contains(perm))
            ret++; // add 1
        ret <<= 1; // shift by 1
    }
    return ret;
}

As to directly preserving the permissions on copy, this is not possible in a single command: SSH makes no guarantee that the filesystem at the remote end supports those, but it does acknowledge that such filesystems exist, which is why it proposes a dedicated command to set permissions on a remote end explicitly.

like image 32
fge Avatar answered Nov 05 '22 13:11

fge