Saturday, February 27, 2010

Shell Script to Upload a File to the Remote FTP Server


#!/bin/bash
# SCRIPT : upload.sh
# USAGE : ./upload.sh [-d remote directory path] -f "File-to-upload"
# -d option is optional by default it takes servers home dir
# or
# ./upload.sh "Filename-to-upload"
#
# PURPOSE : Upload file to remote ftp server.

############### DEFINE FUNCTIONS HERE ##############

Usage()
{
echo " USAGE "
echo " $0 [-d \"Remote Directory Path\"] -f \"Filename-to-upload\""
echo "-------------------------- or -----------------------------"
echo " $0 Filename-to-upload"
exit 1
}

################# ARGUMENTS CHECKING #################

while getopts d:f: choice
do
case $choice in
d) Dname=$OPTARG;;
f) Fname=$OPTARG;;
esac
done

[ $# -eq 1 ] && Fname=$1
[ -z $Dname ] && Dname="/" #change it to suit
[ -z $Fname ] && echo "Bad Arguments" && Usage

[ ! -e $Fname ] && echo "$0: $Fname no such file" && exit 1

############### DEFINE VARIABLES HERE ################

Server="ftp.checksoftware.com" #Remote ftp server.
Username="anonymous" #Remote ftp user name.
Password="venuk@gmail.com" #Remote ftp Password.

# change above to suit

############### MAIN PROGRAM STARTS HERE #############

# Remove comment lines within the here document before run the script

ftp -n $Server <<ServerEnd
user "$Username" "$Password"

# binary command Set the file transfer type to support binary file
# transfer.So you can transfer all type of files.

binary

# hash command is used for printing hash-sign("#") for each data block
# transferred. The size of data block is system dependent.In my box it
# is 1024 bytes. hash command is a toggle switch, by default it is set
# off most systems.

hash # comment it if you don't need it

cd $Dname

# pwd command prints current directory on the remote host. This shows
# your file is uploading to which directory.

pwd # comment it if you don't need it

put "$Fname"
bye
ServerEnd

exit 0

OUTPUT:

[root@www ~]# ./upload.sh
Bad Arguments
USAGE
./upload.sh [-d "Remote Directory Path"] -f "Filename-to-upload"
-------------------------- or -----------------------------
./upload.sh Filename-to-upload
[root@www ~]# ./upload.sh -f samplepic.jpg -d /incoming
Hash mark printing on (1024 bytes/hash mark).
257 "/incoming" is current directory.
###############################################
[root@www ~]# ./upload.sh samplepic.jpg
Hash mark printing on (1024 bytes/hash mark).
257 "/" is current directory.
samplepic.jpg: Permission denied