Python ftp operation script & amp; common functions, pythonftp script

Source: Internet
Author: User
Tags ftp commands ftp site

Python ftp operation script & common functions, pythonftp script

Fast ftp upload, download, and Query files


Use Python to perform ftp server operations

#!/usr/bin/python#ftp.py#this script is used to make some ftp operations more convenient#add upload and download operations  20111210 version0.1import sys,os,ftplib,socketCONST_HOST = "your ftp host or ip"CONST_USERNAME = "your username"CONST_PWD = "your password"CONST_BUFFER_SIZE = 8192COLOR_NONE = "\033[m"COLOR_GREEN = "\033[01;32m"COLOR_RED = "\033[01;31m"COLOR_YELLOW = "\033[01;33m"def connect():  try:    ftp = ftplib.FTP(CONST_HOST)    ftp.login(CONST_USERNAME,CONST_PWD)    return ftp  except socket.error,socket.gaierror:    print("FTP is unavailable,please check the host,username and password!")    sys.exit(0)def disconnect(ftp):  ftp.quit()def upload(ftp, filepath):  f = open(filepath, "rb")  file_name = os.path.split(filepath)[-1]  try:    ftp.storbinary('STOR %s'%file_name, f, CONST_BUFFER_SIZE)  except ftplib.error_perm:    return False  return Truedef download(ftp, filename):  f = open(filename,"wb").write  try:    ftp.retrbinary("RETR %s"%filename, f, CONST_BUFFER_SIZE)  except ftplib.error_perm:    return False  return Truedef list(ftp):  ftp.dir()def find(ftp,filename):  ftp_f_list = ftp.nlst()  if filename in ftp_f_list:    return True  else:    return Falsedef help():  print("help info:")  print("[./ftp.py l]\t show the file list of the ftp site ")  print("[./ftp.py f filenamA filenameB]\t check if the file is in the ftp site")  print("[./ftp.py p filenameA filenameB]\t upload file into ftp site")  print("[./ftp.py g filenameA filenameB]\t get file from ftp site")  print("[./ftp.py h]\t show help info")  print("other params are invalid")def main():  args = sys.argv[1:]  if len(args) == 0:    print("Params needed!")    sys.exit(0)  ftp = connect()  if args[0] == "p":    f_list = args[1:]    for up_file in f_list:      if not os.path.exists(up_file):        print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :file not exist")%up_file)        continue      elif not os.path.isfile(up_file):        print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :%s is not a file")%(up_file,up_file))        continue      if upload(ftp, up_file):        print(("UPLOAD: %s "+COLOR_GREEN+"SUCCESS"+COLOR_NONE)%up_file)      else:        print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE)%up_file)  elif args[0] == "g":    f_list = args[1:]    for down_file in f_list:      if not find(ftp,down_file):        print(("DOWNLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :%s is not in the ftp site")%(down_file,down_file))        continue      if download(ftp, down_file):        print(("DOWNLOAD: %s "+COLOR_GREEN+"SUCCESS"+COLOR_NONE)%down_file)      else:        print(("DOWNLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE)%down_file)  elif args[0] == "l":    list(ftp)  elif args[0] == "f":    f_list = args[1:]    for f_file in f_list:      if find(ftp,f_file):        print(("SEARCH: %s "+COLOR_GREEN+"EXIST"+COLOR_NONE)%f_file)      else:        print(("SEARCH: %s "+COLOR_RED+"NOT EXIST"+COLOR_NONE)%f_file)  elif args[0] == "h":    help()  else:    print("args are invalid!")    help()  disconnect(ftp)if __name__ == "__main__":  main()

Common functions:

You can refer to the following manual for more information:

Login (user = '', passwd ='', acct = '') to log on to the FTP server. All parameters are optional.
Pwd () current working directory
Cwd (path) sets the current working directory to path
Dir ([path [,... [, cb]) displays the content in the path directory. The optional parameter cb is a callback function and is passed to the retrlines () method.
Nlst ([path [,...]) is similar to dir (), but returns a list of file names instead of displaying these file names
Retrlines (cmd [, cb]) is used to download text files by specifying FTP commands (such as "RETR filename. The optional callback function cb is used to process each row of a file.
Retrbinary (cmd, cb [, bs = 8192 [, ra]) is similar to retrlines (), but this command is used to process binary files. The callback function cb is used to process data downloaded from each block (the default block size is 8 KB.
Storlines (cmd, f) specifies the FTP command (such as "STOR filename"), and transmits the text file above. To specify a file object f
Storbinary (cmd, f [, bs = 8192]) is similar to storlines (), but this command is used to process binary files. To specify a file object f, the size of the uploaded part bs is 8Kbs = 8192] by default.)
Rename (old, new) rename the remote file old to new
Delete (path) deletes a remote file in path
Mkd (directory) creates a remote directory


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.