Friday, December 26, 2008

Automating ftp on unix using .netrc

Automating ftp on unix using .netrc

Step One: Creating .netrc in yr home directory
Please create .netrc in your home directory and set permission on the file. It should be unreadable

for everybody except the owner:

#chmod 600 .netrc
#ls -al .netrc
-rw------- 1 pankaj staff 212 Aug 21 11:14 .netrc

#Step two: Contents of .netrc
Contents of .netrc are in two parts, machine info and macros.

Machine definitions:
The first part of the .netrc is filled up with server information:

machine ftp.world.com
login pankaj
password world4me

machine myownmachine
login username
password password

This is as simple as it looks. You are connecting to these servers with these username and passwords.

Now, the second part.

Macro definitions:
This part of the .netrc consists of macros which can be used to perform automated tasks.

macdef mytest
cd /home/pankaj
bin
put filename1.tar.gz
quit

macdef dailyupload
cd /pub/tests
bin
put daily-$1.tar.gz
quit

Keep in mind that there should be an empty line after the last macdef statement. If you don't do this,

ftp will complain about it.

The final .netrc file looks like this now.
machine ftp.world.com
login pankaj
password world4me

macdef mytest
cd /home/pankaj
bin
put filename1.tar.gz
quit

machine myownmachine
login username
password password


macdef dailyupload
cd /pub/tests
bin
put daily-$1.tar.gz
quit

Step Three: Usage of the .netrc
Macros can be called from inside ftp or from the command line.

#ftp myownmachine
ftp: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
220 myownmachine FTP server (Version 6.00LS) ready.
331 Password required for myusername.
230 User myusername logged in.
Remote system type is UNIX.
Using binary mode to transfer files.

ftp> $ uploadtest
cd temp
250 CWD command successful.
put filename.tar.gz
local: filename.tar.gz remote: filename.tar.gz
150 Opening BINARY mode data connection for 'filename.tar.gz'
100% |**************************************************| 1103 00:00 ETA
226 Transfer complete.
1103 bytes sent in 0.01 seconds (215.00 KB/s)
quit
221 Goodbye.

...or from on the command-line:

#echo "\$ uploadtest" | ftp myownmachine
ftp: connect to address ::1: Connection refused
Trying 127.0.0.1...
100% |**************************************************| 1103 00:00 ETA

There is not much information here, because ftp doesn't expect a terminal here. If you use ftp -v,

there will be more output.

An example with arguments is

#echo "\$ dailyupload `date +'%Y%m%d'`"
$ dailyupload 20010827

#echo "\$ dailyupload `date +'%Y%m%d'`" | ftp myownmachine
ftp: connect to address ::1: Connection refused
Trying 127.0.0.1...
100% |**************************************************| 1103 00:00 ETA

It will upload the file daily-20010827.tar.gz.

No comments: