
我的这个文件夹里装满了文件。
每天一次,我希望将最新的文件自动通过 FTP 传输到文件服务器。
答案1
制作一个简短的脚本,通过这一行获取文件名:
newestfilename=`ls -t $dir| head -1`
(假设$dir
是你感兴趣的目录),然后输入$filename
你的FTP命令,当然,cron
这个脚本每天运行一次。
如果有ncftp
,可以对ftp
文件使用以下命令:
ncftpput -Uftpuser -Pftppasswd ftphost /remote/path $dir/$newestfilename
如果没有 ncftp,这可能会起作用:
ftp -u ftp://username:[email protected]/path/to/remote_file $dir/$newestfilename
答案2
找到最新的文件
在目录中查找最新文件的最简单方法是使用 zsh 及其全局限定符 om
按修改时间排序并[1]
选择最近的匹配项。
upload /path/to/dir/*(om[1])
没有好的、便携的方法。唯一可移植的方法是用于ls -t
按日期列出文件并解析结果,但是解析ls
充满危险。仅当您确定文件名不包含换行符或不可打印字符时才执行此操作。
upload "$(ls -t /path/to/dir | head -n 1)"
FTP上传
对于上传,有很多工具。常用的安装方式是卷曲。
curl -T /path/to/local/file ftp://ftp.example.com/remote/dir
另一种方法是将远程目录挂载为文件系统,例如使用卷曲文件系统。
mkdir ftp.example.com
curlftpfs ftp.example.com ftp.example.com
cp -p /path/to/local/file ftp.example.com/remote/dir/
自动化任务
添加一个定时任务每天进入执行任务。运行crontab -e
并添加如下行:
SHELL=/bin/zsh
42 3 * * * curl -T /path/to/dir/*(om[1]) ftp://ftp.example.com/remote/dir
答案3
这是我自制的脚本:
#! /usr/bin/bash
SRCFOLDER="$1"
mountpoint="/home/$(whoami)/ftp"
mkdir "$mountpoint" > /dev/null 2>&1 # temporary ftp path
if [ $(whoami) == "root" ]
then
echo "Dont execute as root!"
exit -1
fi
if [ $# != 1 ]
then
echo "Usage: terser (/source/folder)"
exit 1
fi
if [ "${SRCFOLDER: -1}" != "/" ] # adds a "/" at end of path
then
SRCFOLDER+="/"
fi
if [ -e "$SRCFOLDER" ]
then
FILE=$(ls -t1 $SRCFOLDER | head -n 1)
echo "Newest file is: $FILE"
if [ $FILE == "" ]
then
echo "The folder $SRCFOLDER is empty!"
fi
echo "Mounting ftp..."
curlftpfs "username:[email protected]" "$mountpoint" "-o" "disable_eprt" # if you use tls(port 22) do: "disable_eprt,tlsv1"
echo "Mounted FTP"
echo "Copying to ftp..."
cp "$SRCFOLDER$FILE" "$mountpoint/path/" # after "$mountpoint/" enter your path for your backups
echo "Copied to ftp"
sleep 2
fusermount -u $mountpoint
echo "Unmounted ftp"
sleep 3
rmdir "$mountpoint"
else
echo "The folder $SRCFOLDER does not exist!"
fi
!编辑第 33 行和第 36 行! (ftp 服务器上的 ftp 连接和路径)
只需将其放入 /usr/bin/* 或 /sbin/* 并使用文件名和源文件夹执行即可。例如:
scriptname /home/archuser/backups/
其他方式:
将脚本放入文件中并执行以下操作:
./scriptname /home/archuser/backups/
或者
bash scriptname /home/archuser/backups/
只要为此创建一个 CronJob,你就是一个幸运的人:)