【问题标题】:Secure Copy (scp) the latest file which arrives at a given folder?安全复制 (scp) 到达给定文件夹的最新文件?
【发布时间】:2019-12-27 14:44:03
【问题描述】:

我需要在bash/python 中编写一个脚本到scp 到达给定文件夹的最新文件。也就是说,我不断地将文件放入一个文件夹中,比如说(/home/ram/Khopo/)我需要将它scp 到@ 987654326@/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/)时运行并等待文件到达文件夹并在到达时立即执行

【问题讨论】:

  • Linux 应该有看门狗系统,它可以让您在发生变化时观察文件夹/文件执行功能 - 使用它的 python 模块watchdog。如果系统没有看门狗,那么您可以使用无限循环,在其中检查文件夹并在没有更改时休眠。
  • 如果您想监控远程目录,那么rsync 是一个很棒的工具,但是您必须连续运行才能监控该目录。如果您有可能在远程机器上运行脚本,请在此处查看ionotifywaitsuperuser.com/questions/956311/…

标签: python bash copy scp


【解决方案1】:

【讨论】:

    【解决方案2】:

    正如其他人建议的那样,您可以使用inotifywait,下面是您可以在 bash 中执行的操作的示例:

    #!/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
    

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

    nohup script.sh &
    

    对于sshpass,您可以将其安装在 ubunut/debian 中:

    apt install sshpass
    

    【讨论】:

    • 非常感谢!您能否告诉我如何在 bash 中为 scp 提供密码。我是新人
    • @RAMSHANKERG 有几种方法,我举个例子。如果您满意,请选择此答案作为回复。
    • 另外..我正在复制几种类型的文件...例如文件夹中的文件或单独的文件,我该如何合并所有这些。如果我使用 scp -r 它只复制文件夹,而如果我不使用它,它只复制文件。
    • 我观察到它只复制那些我正在复制到文件夹的文件,那么以编程方式进入它的文件呢?
    • 您可以检查新创建的事件是针对文件还是文件夹。我添加了代码
    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 2015-06-27
    • 2014-12-03
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多