在linux shell中使用ftp命令来实现自动登陆、上传与下载

本文详细介绍了如何通过FTP命令而非交互式的方式,实现Linux FTP服务器上的文件上传。主要关注了使用FTP命令时的-n参数限制自动登录行为,以及通过命令行脚本来自动化执行上传任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前段时间有个需求,需要利用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命令来登陆,然后进入要上传文件的目录,最后开始上传,上传完成后断开连接。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值