13Apr/100
Quick FTP file/directory upload script
Sorry for not posting for a while, school's keeping me busy.
I wrote a small Perl script today to upload a file or a directory to FTP server by command line. Usually I use FileZilla but sometimes you just need something small uploaded fast and don't want to run those resource wasting and slow GUI applications. With my script you just have to pop-up Terminal and type "./up2ftp.pl myimage.png" for example and the file gets uploaded and link to the file gets printed to you.
I also started learning some C#. I'm not much of a Microsoft guy but .Net is getting quite popular.
So here's the FTP upload script:
#!/usr/bin/perl
# up2ftp.pl
# Tue Apr 13 15:09:02 2010
# Copyright 2010 jolttz
# jolttz{ät}gmail{dot}com
#
use strict;
use File::Basename;
use Net::FTP;
# Configuration
my $ftp_adr = "loder.pri.ee"; # FTP address
my $ftp_usr = "username"; # FTP username
my $ftp_pwd = "password"; # Password
my $http_dir = "/public_html"; # Public directory
my $up_dir = "/uploads"; # Upload directory
# Config end
# If $link doesn't get a new value it displays this
my $link = "Error generating link!";
# Connect to host
my $ftp = Net::FTP->new($ftp_adr, Debug => 1)
or die "Can't connect to hostname: $@";
# Identify
$ftp->login($ftp_usr, $ftp_pwd)
or die "Can't login ", $ftp->message;
# Change directory to upload directory
$ftp->cwd($http_dir . $up_dir)
or die "Can't change working directory ", $ftp->message;
# Set binary mode or uploaded images can't be displayed
$ftp->binary();
if ($ARGV[0] eq "-R") {
my $dir = $ARGV[1];
my @dirs = split(/\//, $dir);
my $newdir = @dirs[@dirs-1];
$ftp->mkdir($newdir); # Make new directory
$ftp->cwd($newdir);
# Open local directory to upload
opendir (DIR, $dir) || die "Error in opening dir $dir\n";
while (my $file = readdir(DIR)) {
# If exist upload every file in dir.
if (!-d $file) {
$ftp->put("$dir/$file");
}
}
closedir(DIR);
# Generate link
$link = "http://" . $ftp_adr . $up_dir . "/" . $newdir;
} else {
my $file = $ARGV[0];
my @dirs = split(/\//, $file);
my $filename = @dirs[@dirs-1];
if (!-d $file) {
$ftp->put($file);
$link = "http://" . $ftp_adr . $up_dir . "/" . $filename;
}
}
$ftp->quit();
print "\n" . $link . "\n";
Directory upload syntax:
jolttz@archbox ~ $ perl up2ftp.pl -R /dir/to\ the/dir
File upload syntax:
jolttz@archbox ~ $ perl up2ftp.pl myfile