user3206005
user3206005

Reputation: 13

Automate FTP using Shell Script

I am Using a shell script to transfer files via FTP, my shell works fine. But the problem is my shell script hangs and does not exits if the FTP connection drops down in between the transfer.

this is how my shell script looks like.

echo "open $ip" > ${cmd_File}
echo "user $usrnm $psswd" >> ${cmd_File}
echo "cd $location" >> ${cmd_File}
echo "binary" >> ${cmd_File}
echo "put $filename" >> ${cmd_File}
echo "bye" >> ${cmd_File}

progress=$(ftp -vin < ${cmd_File} 2>&1) 1> /dev/null

I would be glad if someone can help me to handle the error, my code works really fine unless connection drops in between. this code does hangs up there only, I need to exit the code when such a thing happens.

Thanks, Abhijit

Upvotes: 1

Views: 3334

Answers (3)

Cedric Simon
Cedric Simon

Reputation: 4659

I resolved it using lftp instead of ftp.

In my case I was trying to upload files on GoDaddy Online Storage FTP. For some reason the transfer of the biggest file (500 MB) was hanging forever.

Install it as usual (present in main distros): yum install lftp (CentOS) zypper install lftp (openSuse) ...

Then create your script:

#!/bin/sh
echo FTP begin at : $(date)
lftp -u myUser,myPassword myFTPSite <<EOF
put myfile.gz
bye
EOF
echo $(date) : FTP ended

echo Validating RAID
cat /proc/mdstat
exit 0

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207345

Consider rewriting your script using "expect" where you can set a timeout. An example is here. Another example is here.

EDITED:

Alternatively, you could do error checking pretty easily in Perl, like this.

Ok, you can do it in the shell using something along these lines:

YOURTFPCMD & PID=$! ; (sleep $TIMEOUT && kill $PID 2> /dev/null & ) ; wait $PID

which starts your FTP command and saves its PID. It them immediately starts a subshell which will kill your FTP command after $TIMEOUT seconds if it hasn't finished, then waits for your FTP command to exit.

Upvotes: 1

anubhava
anubhava

Reputation: 784888

Use -q quittime option in ftp command:

As per mn ftp:

 -q quittime
             Quit if the connection has stalled for quittime seconds.

Try this command e.g.:

progress=$(ftp -q 30 -vin < ${cmd_File} 2>&1) 1> /dev/null

Upvotes: 0

Related Questions