Wednesday, April 25, 2007

FTP new files to remote server

It has been a while since I have added a good script so here is one that I put together for a friend who needed to send files in a directory that are updated daily to remote client. Have a look at the script and feel free to ask if you don't understand it. This is pretty straight forward.

#!/bin/bash

# Script variables
shopt -s -o xtrace
shopt -s -o vi
shopt -s -o nounset
SPATH="/path/to/script/home"
RUN_LOG="${SPATH}/ftp_log"
SENT_FILE="${SPATH}/send_files_log"

# update date on log files
touch ${RUN_LOG} || {echo "cannot create ftp_log"; exit 1;}
touch ${SENT_FILE} || {echo "cannot create send_files_log"; exit 1;}

# Set home DIR
cd ${SPATH}

# static variables
ALL_FILES=$(ls -l|awk '{if (NR == 1 || $1 ~ /^d/) {next;} print $9}')
DATE="$(date)"

# User defined variables
HOST='10.0.0.1'
USER='user'
PASSWD='password'
TMP_LIST="/tmp/ftp_xfer_log"
REMOTE_DIR="/remote/server/path"

# if tmp list exsists clean it up or create it
if [ -f ${TMP_LIST} ]; then
>${TMP_LIST}
else
touch ${TMP_LIST}
fi


# Create list to send
for file in ${ALL_FILES}
do
grep $file ${SENT_FILE} >/dev/null 2>&1
(($? == 1)) && echo $file >> ${TMP_LIST}
done

# Reformat tmp_list
XFILES="$(echo ${TMP_LIST} | xargs)"

# FTP Files to server
ftp -v -n ${HOST} <quote USER ${USER}
quote PASS ${PASSWD}
prompt
cd ${REMOTE_DIR}
bin
put ${XFILES}
quit
END_SCRIPT

# Place newly sent files into sent list
echo ${TMP_LIST} >> ${SENT_FILE}

# Update Log
echo "" >> ${RUN_LOG}
echo ${DATE} >> ${RUN_LOG}
echo "following files sent successfully" >> ${RUN_LOG}
echo ${TMP_LIST} >> ${RUN_LOG}

# End Script
exit 0

No comments: