I am doing SFTP to transfer files . But during the process , if the path doesn't exists , the sftp is creating a directory bydefault ? Can anyone please explain this to me
1 Answer
With the OpenSSH sftp
client, if the local path of the get
command contains a directory that does not exist, you will get an error.
This is the code (see the do_download()
function in sftp-client.c
):
local_fd = open(local_path,
O_WRONLY | O_CREAT | (resume_flag ? 0 : O_TRUNC), mode | S_IWUSR);
if (local_fd == -1) {
error("Couldn't open local file \"%s\" for writing: %s",
local_path, strerror(errno));
goto fail;
}
No attempt is made to create the directory if it doesn't exist.
Testing this:
sftp> lls hello
ls: hello: No such file or directory
Shell exited with status 1
sftp> get Documents/answers.txt hello/world
Fetching /home/kk/Documents/answers.txt to hello/world
Couldn't open local file "hello/world" for writing: No such file or directory
sftp> lls hello
ls: hello: No such file or directory
Shell exited with status 1
sftp>
If sftp
is started with -r
or if the get
command is used with the same flag, then the destination directory will be created. This is from download_dir_internal()
in sftp-client.c
which is where we end up from process_get()
in sftp.c
if the -r
flag is used:
if (mkdir(dst, mode) == -1 && errno != EEXIST) {
error("mkdir %s: %s", dst, strerror(errno));
return -1;
}
This seems logical to me. If you want to recursively download files, you shouldn't need to manually create the directory structure prior to getting the files.
-
But with
get -r
, the target directory is created, if it does not exist.Martin Prikryl– Martin Prikryl2017-02-13 19:23:12 +00:00Commented Feb 13, 2017 at 19:23 -
@MartinPrikryl Yes. I will update the answer.2017-02-13 19:34:56 +00:00Commented Feb 13, 2017 at 19:34
-
Actually I do not find it logical. It'd say it is rather a side effect of the implementation of the
download_dir_internal
. +1 anywayMartin Prikryl– Martin Prikryl2017-02-13 19:41:45 +00:00Commented Feb 13, 2017 at 19:41 -
@MartinPrikryl No, imagine
cp -r
orrsync -r
requiring you to first do a bunch ofmkdir
calls before you could actually do the copying... You would have to use something like afind /source -type d ...
approach to map the directory structure between the source and the target first, and it would easily become quite messy over a network.2017-02-13 19:46:19 +00:00Commented Feb 13, 2017 at 19:46
sftp
installed with OpenSSH.