SFTP upload file Permission denied

user9219740 picture user9219740 · Feb 11, 2019 · Viewed 18.7k times · Source

I'm trying to upload excel file using SFTP to linux machine from my local windows PC.

Here is my code:

private void uploadToSftp() {
        try
        {
            ChannelSftp sftpClient = null;
            Channel channel = null;
            JSch jsch = new JSch();
            Session session = jsch.getSession("username", "host", 22);
            session.setPassword("password");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking","no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            sftpClient = (ChannelSftp) channel;

            sftpClient.cd("/var/www/folder");
            File localFile = new File("C:\\Workspace\\upload-file\\test.xlsx");
            sftpClient.put(localFile.getAbsolutePath(),localFile.getName());

            sftpClient.disconnect();
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();  
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

but every time i run this application i get error:

3: Permission denied
    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2873)
    at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:594)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:475)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:365)

Doesn anyone know what could be problem and how can i solve this?

Answer

YONGSOO KIM picture YONGSOO KIM · Feb 12, 2019

You seemed to upload your local file "C:\Workspace\upload-file\test.xlsx" to remote directory, "/var/www/folder" on SFTP.

I guess you have all permissions for reading,writing,executing etc on your local file("C:\Workspace\upload-file\test.xlsx"), but your remote folder, "/var/www/folder", might not accept your application's access including "upload" action.

SOLUTION:

The most simplest way to solve this issue is just granting all permission for all users to do anything in your upload target directory("/var/www/folder"). Please try this linux commands for checking permission on your upload folder.

ls -ld /var/www/folder

If you see your /var/www/folder/ directory is not allowed writing or reading(ex:drwxr-xr-x) for normal users, please grant permissions for this folder with the follwing command.

chmod 777 /var/www/folder
//check permission again.
ls -ld /var/www/folder

If you can check the target folder's permission is enough(drwxrwxrwx), please run your application again.

NOTE: Giving all permissions for other users is not considered a good practice. Please just do this solution for test, and change the permission setting fit to your specification later. For more detail, Please check this link(Click).