安全复制(scp)到达给定文件夹的最新文件?

2024-09-30 16:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在bash/python中编写一个脚本到scp最新的文件,它到达给定的文件夹。那个是我不断地把文件放入一个文件夹,比如说(/home/ram/Khopo/),我需要将它scp到xxx@192.168.21.xxx/home/xxx/khopo/。在

我在谷歌上搜索得到了这个结果

file_to_copy=`ssh username@hostname 'ls -1r | head -1'`
echo copying $file_to_copy ...
scp username@hostname:$file_to_copy /local/path

但我想知道是否有可能这样做:它只在新文件夹到达源时运行(/home/ram/Khopo/),并等待文件到达文件夹并在到达时立即执行


Tags: 文件to脚本文件夹bashhomeusernamehostname
2条回答

{cdbashan>在下面的例子中,你可以使用

#!/bin/bash
echo "Enter ssh password"
IFS= read -rs password  # Read the password in a hidden way

inotifywait -m -e create "/folder_where_files_arrive" | while read line
do
    file_to_copy=$(echo $line | cut -d" " -f1,3  output-delimiter="")
    echo copying $file_to_copy ...
    if [[ -d $file_to_copy ]]; then  # is a directory
       sshpass -p $password scp -r username@hostname:$file_to_copy /local/path
    elif [[ -f $file_to_copy ]]; then  # is a file 
       sshpass -p $password scp  username@hostname:$file_to_copy /local/path
    fi
done

然后您最好将此脚本置于后台运行,例如:

^{pr2}$

对于sshpass您可以使用以下方式在ubunut/debian中安装它:

apt install sshpass

相关问题 更多 >