SFTP upload file Permission denied - spring

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?

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).

Related

fs mkdir/copy intermittently fails in protected directory, despite having permissions

I have an electron app on Mac with full disk permissions. I am using fs to make a directory in a protected folder, and copy files from a temp folder to the new directory.
When using fs.copy, I periodically get two different types of errors:
If the directory already exists and is owned by the user:
EPERM errors (operation not permitted, unlink xxx) when attempting to overwrite the existing directory, specifically when replacing a manifest.json file. This is very intermittent.
If the directory does not exist or is owned by root:
EACCES errors when attempting to make the directory or copy files to the new location.
Code:
[...Array(sourceDirs.length).keys()].map(async (idx) => {
try {
await fs.ensureDir(destPaths[idx]);
}
catch (e) {
console.log('Directory does not exist and could not be created');
}
try {
await fs.copy(sourceDirs[idx], destPaths[idx]);
}
catch (e) {
console.log('Copy error:', e);
}
});
After some more research, I determined that the directory's R/W permissions varied based on what entity created the directory. Some elements of the directory and its children were owned by root, and everyone only had read permissions, while other folders were owned by everyone and had write permissions.
Programmatically, the only way to solve this was by spawning a chmod command with sudo to update the permissions. In my case, there isn't any issue with taking ownership of the directory.

Xamarin Download file to - path access denied

We have an issue with downloading any type of file from our server to our phone.
The problem that we have is that we get an access denied error every time we try to save the said file to phone External Memory.
Access to the path "/storage/emulated/0/Download/Test.txt" is denied.
We have given it all the permissions that we found in:
https://developer.android.com/training/data-storage
for both Documents and other files and Media.
Does anyone have any idea why would this be happening? The 'downloading' the file is not the problem, but the saving part is.
After Android 6.0 , we need to request the permissions in runtime . In xamarin , you could use the plugin PermissionsPlugin to request runtime permission .
Usage
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
bool shouldRequest = await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage);
if(shouldRequest)
{
PermissionStatus status = await CrossPermissions.Current.RequestPermissionAsync<StoragePermission>();
if(status==PermissionStatus.Granted)
{
//do something you want
}
else
{
//...
}
}
For more details about the plugin you could check the github project site .

Updating Tomcat WAR file on Windows

I have inherited a Maven/Tomcat(8.5) web application that is locally hosted on different machines. I am trying to get the application to update from a war file that is either stored locally (on a USB drive) or downloaded from AWS on Windows more reliably. On the Linux version, the software is able to upload the new war file via curl using the manager-script by doing the following:
String url = "http://admin:secret#localhost:8080/manager/text/deploy?path=/foo&update=true";
CommandRunner.executeCommand(new String[] { "curl", "--upload-file", war, url });
For Windows, the current current method tries to copy over the war file in the /webapps directory and has tomcat auto deploy the new war file after restarting either tomcat or the host machine. The problem is that the copied war file ends up being 0kb and there is nothing to deploy. This appears to happen outside of my install function because the file size after FileUtils.copyFile() for the /webapps/foo.war is the correct size.
I have tried to implement a PUT request for the manager-script roll from reading the Tomcat manager docs and another post:
File warfile = new File(request.getWar());
String warpath = warfile.getAbsolutePath().replace("\\", "/");
//closes other threads
App.terminate();
String url = "http://admin:secret#localhost:8080/manager/text/deploy?path=/foo&war=file:" + warpath + "&update=true";
HttpClient client = HttpClientBuilder.create().build();
HttpPut request;
try {
request = new HttpPut(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.err.println(result.toString());
} catch (Exception e){
LOGGER.info("war install failed");
throw new ServiceException("Unable to upload war file.", e);
}
However, the process still ends up with a 0kb war file to /webapps. The only error in my log is when tomcat tries to deploy the empty war. I have tried relaxing file read/write permissions in my tomcat installation and it doesn't seem to help. I also don't know if I can guarantee that all Windows installations will have access to curl if I try that implementation. Has anyone ran into similar issues?Thank you for the help!
Will, you are openning the file for sure but you are not writing anything to it, the result string is wrote to the stdout, so you got to replace System.err.println(result.toString()); with fr = new FileWriter(file); br = new BufferedWriter(fr); br.write(result);
and don't forget to close your resources at the end (br.close(); fr.close(); ) :)
PS: check if there are some informations to be filtered (headers or staff like that)

haddop/mapreduce local job directories are not deleted

I just started using hadoop and I noticed that local job directories are not deleted.
I am using hadoop 2.2.0 on Windows .
Is there any configuration that's needed so hadoop can do the clean up of all directories under “/tmp/hadoop-/mapred/local/”?
Also, after investigating and looking in the code, I found that part of the logic is in the the class “org.apache.hadoop.mapred.LocalJobRunner” (hadoop-mapreduce-client-common-2.2.0)
try {
fs.delete(systemJobFile.getParent(), true); // delete submit dir
localFs.delete(localJobFile, true); // delete local copy
// Cleanup distributed cache
localDistributedCacheManager.close();
} catch (IOException e) {
LOG.warn("Error cleaning up "+id+": "+e);
}
Why not just use (as it's the case for systemJobFile):
localFs.delete(localJobFile.getParent(), true); // delete local copy
Is it correct to do that?
I try it and looks like it's fixing the issue, but I am not sure.
Update: I just noticed that a lot of directories "attempy_local****" are still there. Not deleted by hadoop!
Thank you.
As I have to find a quick solution and I don't like the idea to create a script to clean-up these directories, I did this patch (org.apache.hadoop.mapred.LocalJobRunner):
// line: 114
private Path localCacheJobDir;
// line: 156
this.localCacheJobDir = localFs.makeQualified(new Path(new Path(new Path(conf.getLocalPath(jobDir), user), JOBCACHE), jobid.toString()));
// line: 492
try {
fs.delete(systemJobFile.getParent(), true); // delete submit dir
final Path localJobFilePath = localJobFile.getParent();
localFs.delete(localJobFile, true); // delete local copy
// Cleanup distributed cache
localDistributedCacheManager.close();
localFs.delete(localJobFilePath, true); // delete local copy
localFs.delete(localCacheJobDir, true); // delete local copy
} catch (IOException e) {
LOG.warn("Error cleaning up "+id+": "+e);
}
I have never worked with hadoop before and I just started playing with in the last two days, so I don't know if my solution won't have any impact on hadoop. Unfortunatly this is the best solution I have.
There are some configuration keys like
mapreduce.task.files.preserve.failedtasks
in mapred config.
Anyway...
By default hadoop should clear the temporary job directory.
On success the files are moved to ${mapreduce.output.fileoutputformat.outputdir}
If things gone wrong, files are deleted.
So I'm not sure this fix for real what is happening on your installation.

File Write - Unauthorized Access Exception

Trying to save a file locally from an app running in the iOS 8 Simulator and I'm continually getting access denied exceptions.
In previous apps I've used the following code to get a valid file path:
Environment.GetFolderPath(Environment.SpecialFolder.Personal)
or
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
But I've read that with iOS 8 this has now got to be written as:
NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomain.User)[0]
So I'm using the following code to generate a file path for a .txt file and receiving an access denied exception when trying to save with it:
public void SaveMyFile(string content)
{
NSUrl[] urls;
string filePath;
//
urls = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomain.User);
filePath = Path.Combine(urls[0].Path, "MyApp", "myFile.txt");
File.WriteAllText(filePath, content);
}
So the file path that it gives me and also denies access to is /Users/Idox/Library/Developer/CoreSimulator/Devices/92498E38-7D50-4081-8A64-83061DC00A86/data/Containers/Data/Application/C35B3E98-C9E3-4ABA-AA7F-CD8419FA0EA5/Documents/MyApp/myFile.txt.
I'm wondering if there's some setting that needs to be toggled to give the app write access to this directory or if the directory itself is invalid.
I've also done a call to Directory.Exists(string path) to check if the directory is there, which it is.
You're missing the Path property on urls[0].Path
filePath = Path.Combine(urls[0].Path, "MyApp", "myFile.txt");
This was fixed in Xamarin.iOS 8.4, so if you're using a recent version of Xamarin you can use Environment.GetFolderPath without problems (which is useful if you want to share code across platforms).

Resources