日期:2014-05-16  浏览次数:20657 次

linux 编写shell脚本,FTP命令自动上传下载


前段时间有个需求,需要利用crontab定时往某个FTP上传文件,原以为linux中带的ftp命令只支持交互式的操作,没法在命令行下使用,所以后来打算利用PHP中提供的ftp命令来做,但是很不幸的发现ftp模块不是PHP的标准模块,还需要自己编译,比较麻烦,后来本着试试看的态度去网上搜了一把,结果发现还真是可以在shell下来利用ftp命令。

首先我们来看ftp的两个参数

-n     Restrains  ftp from attempting ''auto-login'' upon initial connection.  If auto-login is enabled, ftp will check
              the .netrc (see below) file in the user's home directory for an  entry  describing  an  account  on  the  remote
              machine.  If no entry exists, ftp will prompt for the remote machine login name (default is the user identity on
              the local machine), and, if necessary, prompt for a password and an account with which to login.

-u     Restrains ftp from attempting  ''auto-authentication''  upon  initial  connection.   If  auto-authentication  is
              enabled, ftp attempts to authenticate to the FTP server by sending the AUTH command, using whichever authentica-
              tion types are locally supported.  Once an authentication type is accepted, an authentication protocol will pro-
              ceed by issuing ADAT commands.  This option also disables auto-login.

显然默认情况下,我们不加这两个参数来使用ftp命令的话,如ftp localhost,那么就直接被要求用户名和密码,这样子就走回到交互式的老路上去了。因此要使用非交互式就必须加-n这个参数,(-u不是必须的,如果不加的话,对于一些服务器可能会报一个warning,但是不影响功能)。最终shell脚本如下所示这样子

ftp –u –n $HOST $PORT << CMDS

user $USERNAME $PASSWORD

lcd $DST_FOLDER

put $DST_FILENAME

bye

TAG

这段脚本就告诉ftp命令,不自动登陆,连接到$HOST的$PORT端口,然后依次运行TAG里标注的命令

我们这里是先运行user命令来登陆,然后进入要上传文件的目录,最后开始上传,上传完成后断开连接。