Linux/Ubuntu Bash Script to Send All Files in a directory via SFTP

The following script can be scheduled as a “CRON JOB”. It looks at all files (optionally with a file mask) in a given directory, and sends them to a specific SFTP site.

This example uses a private key, and the name of that key file is passed as the -i argument on the stp command line.

There “here doc” from << EOF to the line starting with EOF, is used to pass STDIN (standard input) to the SFTP command. It keeps a simple log of all files sent by just using the "echo' command to append the date time, the script name, and the filename on the log.txt file. If you are not familiar with BASH scripts, everything between the "do" and the "done" is subject the for loop in the example below. The "for" loop iterates and returns all the files in the given directory name (in a variable called $filename).

#!/bin/bash
for filename in /home/nealwalters/downloads/*.csv; do 
   currentDate=`date` 
   echo "Loop: Filename=$filename" 
   echo "$currentDate SFTPUser3 Filename=$filename" >> /home/nealwalters/scripts/log.txt

   sftp -i /home/nealwalters/keys/SFTPUser1_Private.pem SFTPUser3@192.168.1.179 << EOF
      cd User3ToMyCompany
      put $filename
      exit
EOF
   echo "----------------------------------------------------------------"
done

From my 10 hour course: Udemy Course:SFTP Client Server Deep Dive with OpenSSH (both Unix and Windows) and BizTalk

Uncategorized  

Leave a Reply