Ftp Script

Posted on 2004-09-07
Last Modified: 2010-08-05
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.

Question by:TPoly
  • 2

Expert Comment

ID: 12005603
can your find your text files easily by the filename? as in get all the files ending with .TXT?

Author Comment

ID: 12012209
no and  it does not end with .TXT

the file name is jus

"trayReport" and "yieldReport"

Accepted Solution

g0rath earned 180 total points
ID: 12016726

"""FTP a file script

Usage: [options] [filename]

      -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 = ''
            self.Port = 21
            self.user = 'anonymous'
            self.password = ''
            self.dir = '/Pub'
            self.dnldir = '/tmp'
            self.isConnected = 0
      def connect(self):
                  self.isConnected = 1
                  print "Error connecting:",sys.exc_info()[0]
      def close(self):
                  print "Error closing:",sys.exc_info()[0]
      def sendFile(self,FileName):
            if self.isConnected == 0:
                  print 'Sending file: %s' % ( FileName )
                  self.ftp.storbinary('STOR ' + FileName,open(FileName,'rb'))
                  print "Error sending file:",sys.exc_info()[0]
      def getAllFiles(self):
                  if self.isConnected == 0:
                  files = self.ftp.nlst()
                  for file in files:
            except ftplib.error_perm,msg:
                  print "FTP Error: ", msg
                  print "Error getting file:",sys.exc_info()[0]
      def chdir(self,Dir):
                  self.dir = Dir
            except ftplib.error_perm,msg:
                  print "FTP Error: ", msg
                  print "Error getting file:",sys.exc_info()[0]
      def getFile(self,FileName):
            if self.isConnected == 0:
                  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
                  print "Error getting file:",sys.exc_info()[0]
def usage(code,msg=''):
      print >> sys.stderr,__doc__
      if msg:
            print >> sys.stderr, msg

# The actual program
def main():
            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'):
            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!'

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

if __name__ == '__main__':


Here is a ftp script written in python

usage like so: -S -r /pub/linux/kernel/v2.6 -g linux-2.6.8.tar.gz

This will connect to anonymous and get the file 'linux-2.6.8.tar.gz' -S -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 -S -u realUser -p realPassword -r /pub/Stuff -l /tmp -g afile.txt

download afile.txt and put it in /tmp when done -S -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

Assisted Solution

GP1628 earned 20 total points
ID: 12028590
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:

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Have you ever been frustrated by having to click seven times in order to retrieve a small bit of information from the web, always the same seven clicks, scrolling down and down until you reach your target? When you know the benefits of the command l…
The purpose of this article is to fix the unknown display problem in Linux Mint operating system. After installing the OS if you see Display monitor is not recognized then we can install "MESA" utilities to fix this problem or we can install additio…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question