我想从 ftp 服务器下载文件。我已确认我具有访问权限,因为我可以使用 Chrome 手动下载文件以列出 ftp 目录内容,然后单击每个文件,一次下载一个文件。不过,文件很多,我想使用curl 来为我抓取所有文件。
但是,ftp 服务器的设置使我无法访问
Parent
目录,即使我确实可以访问 Child
目录,因此以下 curl
命令失败:
curl -u username:password "ftp://example.com/Parent/Child/file.txt" -o file.txt
详细 (
-v
) 输出的关键摘录:
< 230 User logged in.
> PWD
* Entry path is '/'
> CWD Parent
< 550 Access is denied
* Server denied you to change to the given directory
curl: (9) Server denied you to change to the given directory
有什么方法可以让curl直接更改到最终目录而不是遍历层次结构,以避免在不允许的父目录上出现错误?
是的,可以。 Curl 的工作原理是在每个
/
字符上分割路径,然后一次发出一个 PWD
命令(正如您从详细输出中看到的那样)。
只需使用
/
对中间 %2f
字符进行 urlencode,curl 将立即发出 CWD
命令:
$ curl -u username:password "ftp://example.com/Parent%2fChild/file.txt" -o file.txt
> CWD Parent/Child
< 250 CWD command successful.
瞧!
从curl 7.15.1开始,可以选择使用
--ftpmethod <method>
。
选项有:
就我而言,我使用:
curl -vs -o - -u user:pass --ftp-method nocwd ftp://example.com/path/to/file/test.txt
命令输出:
* Trying example.com:21...
* Connected to example.com (example.com) port 21 (#0)
< 220 (vsFTPd 3.0.3)
> USER user
< 331 Please specify the password.
> PASS pass
< 230 Login successful.
> PWD
< 257 "/home/user" is the current directory
* Entry path is '/home/user'
> EPSV
* Connect data stream passively
* ftp_perform ends with SECONDARY: 0
< 229 Entering Extended Passive Mode (|||8005|)
* Trying example.com:8005...
* Connecting to example.com port 8005
* Connected to example.com port 21 (#0)
> TYPE I
< 200 Switching to Binary mode.
> SIZE /home/user/path/to/file/test.txt
< 213 11
> RETR /home/user/path/to/file/test.txt
< 150 Opening BINARY mode data connection for /home/user/path/to/file/test.txt (11 bytes).
* Maxdownload = -1
* Getting file with size: 11
testmessage
< 226 Transfer complete.
请参阅 curl 手册页了解更多详细信息。