You only need the 4 details from the destination server:
- Destination Server IP
- Destination Port where you are connected into (by default is 22)
- FTP Account Username
- FTP Account Password.
Lets assume you have now the credentials and your server is allowed to connect to destination server via the IP and Port provided. We can now develop the script that will transfer files from your server to destination server.
Just follow the simple steps below with the complete code at the end for your reference.
1. We need the FTP library to be installed in your server.
- Net::FTP
$ftp = Net::FTP->new([DESTINATION SERVER IP],Port=>[DESTINATION SERVER PORT]);
3. You can also get the return message or status of every object call by calling $object->message. The $object is the return object on step #2.
$ftp->message;
4. Submit the login credentials by calling $object->login(<username>, <password>).
$ftp->login([USERNAME], [PASSWORD]);
5. If successful, you can change or create your destination working directory by executing $object->cwd(<directory>) or $object->mkdir(<directory>).
$ftp->cwd($ftp_dir) or $ftp->mkdir($ftp_dir);
6. If your okay with your working directory, you can now transfer files from your server to destination server by calling $object->put(<source file>, <destination file>).
$ftp->put("[FILEPATH AND FILENAME OF SOURCE SERVER]", "[FILENAME OF DESTINATION SERVER]");
7. Then close the connection by calling $object->quit.
$ftp->quit;
That's it!! Hope you were able to follow the 7 simple steps above. You can also get the complete code with added functionality to support temporary files and renaming. Please see below.
#!/usr/bin/perl
use Net::FTP;
$ftp_ip = "<your destination ip>";
$ftp_port = "<your destination port>";
$ftp_user = "<your ftp account username>";
$ftp_pass = "<your ftp account password>";
$ftp_dir = "<your destination working directory>";
$ftp_src_file = "<your source file to be transfered include the full source path>";
$ftp_dest_file_temp = "<your temporary destination filename>";
$ftp_dest_file_good = "<your final destination filename>";
# create new instance
$ftp = Net::FTP->new($ftp_ip,Port=>$ftp_port) || die "ERROR: Unable to connect to host [$ftp_ip:$ftp_port]";
var_dump($ftp->message);
# login
$ftp->login($ftp_user, $ftp_pass) || die "ERROR: Unable to login [$ftp_user]";
var_dump($ftp->message);
# change working directory
$ftp->cwd($ftp_dir) or $ftp->mkdir($ftp_dir);
var_dump($ftp->message);
# transfer files
$ftp->put("$ftp_src_file", "$ftp_dest_file_temp") || die "ERROR: Transfer failed!",$ftp->message;
var_dump($ftp->message);
# rename files
$ftp->rename("$ftp_dest_file_temp", "$ftp_dest_file_good") || die "ERROR: Rename Failed!",$ftp->message;
var_dump($ftp->message);
# closing the ftp connection
$ftp->quit;
echo "done!";
1;
No comments:
Post a Comment