Ftp Script

hi ...

i would like to ftp text files over to a remote computer.

The text files that i want to ftp over are all stored in a directory and sub-directories with
other types of files (eg .dat).

I do not know the file name of the textfile until after transferring.

I would like to ask if it is possible to just ftp the text files from the directory and sub-diectories over to the remote computer. And stored it in a folder that i had created. It should also be able to delete the contents in the directory.


thanks....  
TPolyAsked:
Who is Participating?
 
g0rathConnect With a Mentor Commented:
#!/bin/python

"""FTP a file script

Usage: ftp.py [options] [filename]

Options:
      -h / --help
            Print this message and exit.

      -S / --server=Server Name
            FTP Server

      -P / --port=FTP Port
            FTP Port      

      -u / --username=username
            Account for ftp

      -p / --password=password
            Account password

      -l / --localdir=Local directory
            Local directory for recieving or sending files
      
      -r / --remotedir=Remote directory
            Remote FTP directory for recieving or sending files
      
      -g / --get
            get file
      
      -s / --send
            send file
      
"""

from ftplib import FTP
import os,string,sys,shutil,getopt,ftplib


class myFTP:
      def __init__(self):
            self.ftp = FTP()
            self.Server = '127.0.0.1'
            self.Port = 21
            self.user = 'anonymous'
            self.password = 'expert@experts-exchange.com'
            self.dir = '/Pub'
            self.dnldir = '/tmp'
            self.isConnected = 0
      def connect(self):
            try:
                  self.ftp.connect(self.Server,self.Port)
                  self.ftp.login(self.user,self.password)
                  self.chdir(self.dir)
                  self.isConnected = 1
            except:
                  print "Error connecting:",sys.exc_info()[0]
                  raise
      def close(self):
            try:
                  self.ftp.close()
            except:
                  print "Error closing:",sys.exc_info()[0]
                  raise
      def sendFile(self,FileName):
            if self.isConnected == 0:
                  self.connect()
            try:
                  self.ftp.cwd(self.dir)
                  print 'Sending file: %s' % ( FileName )
                  self.ftp.storbinary('STOR ' + FileName,open(FileName,'rb'))
            except:
                  print "Error sending file:",sys.exc_info()[0]
                  raise
      def getAllFiles(self):
            try:
                  if self.isConnected == 0:
                        self.connect()
                  files = self.ftp.nlst()
                  for file in files:
                        self.getFile(file)
            except ftplib.error_perm,msg:
                  print "FTP Error: ", msg
            except:
                  print "Error getting file:",sys.exc_info()[0]
                  raise
      def chdir(self,Dir):
            try:
                  self.dir = Dir
                  self.ftp.cwd(self.dir)
            except ftplib.error_perm,msg:
                  print "FTP Error: ", msg
            except:
                  print "Error getting file:",sys.exc_info()[0]
                  raise
      def getFile(self,FileName):
            if self.isConnected == 0:
                  self.connect()
            try:
                  print "Getting file: %s" % ( FileName )
                  self.ftp.retrbinary('RETR ' + FileName,open(FileName,'wb').write)
                  shutil.move(FileName,'%s/%s' % (self.dnldir,FileName))
            except ftplib.error_perm,msg:
                  print "FTP Error: ", msg
            except:
                  print "Error getting file:",sys.exc_info()[0]
                  raise
def usage(code,msg=''):
      print >> sys.stderr,__doc__
      if msg:
            print >> sys.stderr, msg
      sys.exit(code)

# The actual program
def main():
      try:
            opts, args = getopt.getopt(sys.argv[1:],'hu:S:p:Pr:l:gs',['help','username=','server=','password=','port=','remotedir=','localdir=','get','send'])
      except getopt.error, msg:
            usage(1, msg)

      F = myFTP()
      fileOp = -1

      for opt, arg in opts:
            if opt in ('-h', '--help'):
                  usage(0)
            elif opt in ('-u', '--username'):
                  F.user = arg
            elif opt in ('-S', '--server'):
                  F.Server = arg
            elif opt in ('-p', '--password'):
                  F.password = arg
            elif opt in ('-P', '--port'):
                  F.Port = arg
            elif opt in ('-r', '--remotedir'):
                  F.dir = arg
            elif opt in ('-l', '--localdir'):
                  F.dnldir = arg
            elif opt in ('-g', '--get'):
                  fileOp = 0
            elif opt in ('-s', '--send'):
                  fileOp = 1

      if os.path.exists(F.dnldir) == 0:
            print 'Path: ' + F.dnldir + ' does not exist!'
            sys.exit(1)

      if fileOp == 0:
            if len(args) == 0:
                  F.getAllFiles()
            for file in args:
                  F.getFile(file)
      elif fileOp == 1:
            for file in args:
                  F.sendFile(file)
      elif fileOp == -1:
            print >> sys.stderr, 'No operation selected, need -g or -s'
            sys.exit(1)
      F.close()

if __name__ == '__main__':
      main()

#---------------SNIP--------------------

Here is a ftp script written in python


usage like so:


ftp.py -S ftp.kernel.org -r /pub/linux/kernel/v2.6 -g linux-2.6.8.tar.gz

This will connect to ftp.kernel.org anonymous and get the file 'linux-2.6.8.tar.gz'

ftp.py -S 127.0.0.1 -u realUser -P 1033 -p realPassword -r /pub/Stuff -g

This will connect to local host port 1033 with username, password stuff and directory and get all files since you didn't specify any files

ftp.py -S 127.0.0.1 -u realUser -p realPassword -r /pub/Stuff -l /tmp -g afile.txt

download afile.txt and put it in /tmp when done

ftp.py -S 127.0.0.1 -u realUser -p realPassword -r /pub/Stuff -s /home/expert/www/index.html

send the file index.html to the server and store it in /pub/Stuff

This script was written and debugged using python 2.3.4
0
 
g0rathCommented:
can your find your text files easily by the filename? as in get all the files ending with .TXT?
0
 
TPolyAuthor Commented:
no and  it does not end with .TXT

the file name is jus

"trayReport" and "yieldReport"
0
 
GP1628Connect With a Mentor Commented:
It would be fairly easy to write a script for that but ftp itself doesnt have the option. Possibly some sort of sync or mirroring software does.

Hmmm if I were to do this I think I would use the "files" command to check for ascii type files, then use the result to build an ftp list. Try this just as a starter and see if it lists the files you want...
 file * | grep -i asci | cut -f1 -d:
0
All Courses

From novice to tech pro — start learning today.