perl自动ftp的方法(Linux版本,Net::FTP)

来源:互联网 发布:python中reload未定义 编辑:程序博客网 时间:2024/05/21 18:27
在很多情况下,我们需要从远处服务器上下载当天或者昨天生成的日志文件,来查看一些我们需要的东西或者备份。
    如果采用了ftp,那么我们应该建立自动化的ftp方式,来方便我们的工作,下面我们将使用perl语言编写的,当然也可以用shell。
    利用了perl的模块:Net::FTP。
#!/usr/bin/perl
use Net::FTP;
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime();
$year=$year+1900;  #显示为当前年份
$mon=$mon+1;       #显示为当前月份
$mon = "0".$mon if ($mon < 10);   #显示月份为 01,02的格式
$sum="$year-$mon-$mday";  #显示时间 为 2008-12-22 这样的格式

$ftp = Net::FTP->new("hostname(IP地址)", Debug =>1);


$ftp->login('user(用户名)','passwd(密码)');
$ftp->binary;
$ftp->cwd("path(路径)");
$ftp->get("$sum-filename(文件名)")  #比如 2008-12-22_text.txt
      or die "$!";

$ftp->quit;

保存后。给文件加上执行。利用 chmod命令。(我们暂时把执行文件叫做 Ftp.pl)
在来设置例行性命令  利用crontab命令。
比如 你想早上5点半开始执行下载。则加入
30 05 * * *  perl Ftp.pl

保存。则程序就开始自动化ftp了。

$ftp->put("$sum-filename(文件名)")  #比如 2008-12-22_text.txt  为上传
      or die "$!";


##################################

use Net::FTP;
$ftp=Net::FTP->new("$FTP_ADDR",Timeout=>30) or die "Could not connect.\n";
#登录到FTP
$ftp->login($FTP_username,$FTP_pass) or die "Could not login.\n";
#切换目录
$ftp->cwd("/$FTP_dir[0]") ,$FTP_error=$ftp->message;
if ( $FTP_error =~ /Failed/){
print  "FTP返回目录不存在错误信息,开始创建目录$FTP_dir[0]...,\n";
$ftp->mkdir($FTP_dir[0]);
print "$FTP_dir[0]目录创建完毕..并切换到目录创建目录,\n";
$ftp->cwd("/$FTP_dir[0]");
print "开始上传文件$file...\n";
$ftp->put($file) or die "上传$file失败。。。,\n";
$ftp->put($charactorfile) or die "上传$charactorfile失败。。。,\n";
$ftp->put($accountfile) or die "上传$accountfile失败。。。,\n";
$ftp->quit;
}
else
{
$ftp->put($file) or die "上传$file失败。。。,\n";
$ftp->put($charactorfile) or die "上传$charactorfile失败。。。,\n";
$ftp->put($accountfile) or die "上传$accountfile失败。。。,\n";
$ftp->quit;
}
print "上传文件$file,$charactorfile,$accountfile至FTP的$FTP_dir[0]完成。。。,\n";



原创粉丝点击