Search code examples
pythonbashcopyscp

Secure Copy (scp) the latest file which arrives at a given folder?


I need to write a script in bash/python to scp the latest file which arrives at a given folder.That is I am continously getting files into a folder say (/home/ram/Khopo/) I need to scp it into xxx@192.168.21.xxx in /home/xxx/khopo/.

I googled and got this result

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

But I want to know whether it is possible do this such that it runs only when a new folder arrives at the source(/home/ram/Khopo/) and waits for the file to reach the folder and do it immediately when it has arrived


Solution

  • As others have suggested you can use inotifywait, below an example of what you could do in 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
    

    Then you would ideally put this script to run in background, e.g.,:

    nohup script.sh &
    

    For sshpass you can install it in ubunut/debian with:

    apt install sshpass