I have a perl script written in Server B to scp a file periodically for every hour from Server A to Server B. The problem is sometimes the scp fails for that particular hour because of some issues on the server B. I want the scp to keep retrying until it succeeds whenever this happens.

The script is:

$soc_scp=`scp -r user\@some_ip:\/home\/hbase\/hourly\/$datehr\.tar\.gz \/home\/hbase\/hourly\/$datehr\.tar\.gz`;


$echo_soc=`echo $?`;

if($echo_soc != 0)
{
$soc_scp=`scp -r user\@some_ip\:\/home\/hbase\/hourly\/$datehr\.tar\.gz \/home\/hbase\/hourly\/$datehr\.tar\.gz`;
}

I have not specified the ip for security reasons.Any help would be much appreciated.

有帮助吗?

解决方案

Instead of the backticks, try calling scp with system(). That captures scp's exit status instead of its output. Then you can check it and retry if it was nonzero.

sleep 1 while system "scp -r user\@some_ip:/home/hbase/hourly/$datehr.tar.gz /home/hbase/hourly/$datehr.tar.gz";

This will try scp forever at 1s intervals until success.
To limit the number of tries to 10:

my $tries = 0;
while (system "scp -r user\@some_ip:/home/hbase/hourly/$datehr.tar.gz /home/hbase/hourly/$datehr.tar.gz") {
    last if $tries++ > 10;
    sleep 1;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top