Windows 下涉及 Ftp 命令的批处理写法

September 5th, 2009 | Tags:

今天想写一个批处理文件,其功能是从一个指定的 Ftp 服务器上把某个目录下的所有文件都下载下来,结果发现遇到个难题。

我本来是这样写的

C:>cat Batch.bat
@echo off && @color 0A & cls
ftp 1.1.1.1
cd /pub/files/
mget *.*

一运行,发现批处理运行到 ftp 1.1.1.1 这条命令后就出现了要求输入用户名和密码的提示。刚开始尝试替换为如下形式

ftp -a 1.1.1.1
ftp USERNAME:PASSWORD@1.1.1.1
ftp ftp://USERNAME:PASSWORD@1.1.1.1#匿名时用户名为 anonymous ,密码为空

均告失败。其中第一条的 -a 参数无效(*nix 系统中 -a 表示匿名访问,Windows 中不是),第二条和第三条报告 Unknown Host 错误。

后来在 http://technet.microsoft.com 中找到了官方的 Ftp 命令帮助页面,内容如下

ftp [-v] [-d] [-i] [-n] [-g] [-s:FileName] [-a] [-w:WindowSize] [-A] [Host]

Parameters
-v : Suppresses the display of FTP server responses.
-d : Enables debugging, displaying all commands passed between the FTP client and FTP server.
-i : Disables interactive prompting during multiple file transfers.
-n : Suppresses the ability to log on automatically when the initial connection is made.
-g : Disables file name globbing. Glob permits the use of the asterisk (*) and question mark (?) as wildcard characters in local file and path names. For more information, see Ftp: Glob
-s: FileName : Specifies a text file that contains ftp commands. These commands run automatically after ftp starts. This parameter allows no spaces. Use this parameter instead of redirection (< ).
-a : Specifies that any local interface can be used when binding the FTP data connection.
-w: WindowSize : Specifies the size of the transfer buffer. The default window size is 4096 bytes.
-A : Logs onto the FTP server as anonymous.
Host : Specifies the computer name, IP address, or IPv6 address of the FTP server to which to connect. The host name or address, if specified, must be the last parameter on the line.
/? : Displays help at the command prompt.

发现两个问题:
1,-a 指的是 interface,真难理解,难道是指定网卡或网络连接?
2,-A 才是匿名访问
3,Ftp 命令专门提供了一个 -s:FileName 参数以便登录进入服务器之后调出使用。

现在好办了,原批处理文件内容修改如下

C:>cat Batch.bat
@echo off && @color 0A & cls
ftp -A 1.1.1.1
cd /pub/files/
mget *.*

再运行一次,好了,顺利登录,但登录进入服务器之后没有自动运行后两条命令,这好办,利用 -s 命令即可。先在同目录下创建一个文本文件,文件名取为 commands.ini(与文件后缀无关),内容如下

C:>cat commands.ini
cd /pub/files
mget *.*

然后,把 Batch.bat 文件修改如下

C:>cat Batch.bat
@echo off && @color 0A & cls
ftp -s:commands.ini 1.1.1.1

再次运行之后,基本上达到了预期的目标,后来再经改进,版本如下

C:>cat Batch.bat
@echo off && @color 0A & cls
start ftp -s:commands.ini 1.1.1.1 #用 start 命令把 Ftp 动作给 fork 出来,以便继续执行下面的命令
OTHER LOCAL COMMANDS #任意本地命令
C:>cat commands.ini
USERNAME #只写用户名,不能再前面加 user 命令
PASSWORD #如果密码为空,则此行为空;必须保留这一行
cd /pub/files
prom #关闭提示,否则 mget 每次下载文件前都要手工判断 YES or NO
mget *.*

注意
此处的 cat 命令等同于 type 命令
“#” 号是注释符,仅供阅读方便

相关链接
Ftp

No comments yet.