python ftp操作腳本&常用函數

火星人 @ 2014-03-03 , reply:0


python ftp操作腳本&常用函數

python ftp操作腳本&常用函數



需求:快速進行ftp上傳 ,下載,查詢文件


原來直接在shell下操作:

需要【連接,輸用戶名,輸密碼,單文件操作,存在超時限制】

太過於繁瑣,容易操作失敗




腳本改進:

一句命令,搞定多文件上傳,下載,查詢,列表等操作

後期可以加入更強大的功能




直接上腳本:view plaincopy to clipboardprint?
#!/usr/bin/python   
#ftp.py   
#this script is used to make some ftp operations more convenient   
#add upload and download operations  20111210 version0.1   
  
import sys,os,ftplib,socket  
  
CONST_HOST = "your ftp host or ip"  
CONST_USERNAME = "your username"  
CONST_PWD = "your password"  
CONST_BUFFER_SIZE = 8192  
  
COLOR_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 True  
  
def 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 True  
  
def list(ftp):  
  ftp.dir()  
  
def find(ftp,filename):  
  ftp_f_list = ftp.nlst()  
  if filename in ftp_f_list:  
    return True  
  else:  
    return False  
  
def 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  
  if len(args) == 0:  
    print("Params needed!")  
    sys.exit(0)  
  
  ftp = connect()  
  
  if args == "p":  
    f_list = args  
    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 == "g":  
    f_list = args  
    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 == "l":  
    list(ftp)  
  elif args == "f":  
    f_list = args  
    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 == "h":  
    help()  
  else:  
    print("args are invalid!")  
    help()  
  
  disconnect(ftp)  
  
  
  
if __name__ == "__main__":  
  main()  
#!/usr/bin/python
#ftp.py
#this script is used to make some ftp operations more convenient
#add upload and download operations  20111210 version0.1

import sys,os,ftplib,socket

CONST_HOST = "your ftp host or ip"
CONST_USERNAME = "your username"
CONST_PWD = "your password"
CONST_BUFFER_SIZE = 8192

COLOR_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 True

def 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 True

def list(ftp):
  ftp.dir()

def find(ftp,filename):
  ftp_f_list = ftp.nlst()
  if filename in ftp_f_list:
    return True
  else:
    return False

def 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
  if len(args) == 0:
    print("Params needed!")
    sys.exit(0)

  ftp = connect()

  if args == "p":
    f_list = args
    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 == "g":
    f_list = args
    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 == "l":
    list(ftp)
  elif args == "f":
    f_list = args
    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 == "h":
    help()
  else:
    print("args are invalid!")
    help()

  disconnect(ftp)



if __name__ == "__main__":
  main()常用函數:

用手冊查看,以下只是簡略,因為沒用用到,[待整理]:

login(user='',passwd='', acct='') 登錄到FTP 伺服器,所有的參數都是可選的
pwd()                    當前工作目錄
cwd(path)                把當前工作目錄設置為path
dir(])    顯示path 目錄里的內容,可選的參數cb 是一個回調函數,會被傳給retrlines()方法
nlst() 與dir()類似,但返回一個文件名的列表,而不是顯示這些文件名
retrlines(cmd [, cb]) 給定FTP 命令(如「RETR filename」),用於下載文本文件。可選的回調函數cb 用於處理文件的每一行
retrbinary(cmd, cb[,bs=8192[, ra]]) 與retrlines()類似,只是這個指令處理二進位文件。回調函數cb 用於處理每一塊(塊大小默認為8K)下載的數據。
storlines(cmd, f) 給定FTP 命令(如「STOR filename」),以上傳文本文件。要給定一個文件對象f
storbinary(cmd, f[,bs=8192]) 與storlines()類似,只是這個指令處理二進位文件。要給定一個文件對象f,上傳塊大小bs 默認為8Kbs=8192])
rename(old, new) 把遠程文件old 改名為new
delete(path) 刪除位於path 的遠程文件
mkd(directory) 創建遠程目錄
《解決方案》

學習鳥  謝謝分享
《解決方案》

多謝分享 寫得很好:)
《解決方案》

學習了,謝謝




[火星人 via ] python ftp操作腳本&常用函數已經有282次圍觀

http://www.coctec.com/docs/service/show-post-1255.html