Solved

Ftp Script

Posted on 2004-09-07
4
464 Views
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.


thanks....  
0
Comment
Question by:TPoly
  • 2
4 Comments
 
LVL 5

Expert Comment

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

Author Comment

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

the file name is jus

"trayReport" and "yieldReport"
0
 
LVL 5

Accepted Solution

by:
g0rath earned 180 total points
ID: 12016726
#!/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
 
LVL 2

Assisted Solution

by:GP1628
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:
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

757 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now