用python写测试脚本,从本地传文件至ftp远程路径

Python09

用python写测试脚本,从本地传文件至ftp远程路径,第1张

转自:http://news.tuxi.com.cn/kf/article/jhtdj.htm

本文实例讲述了python实现支持目录FTP上传下载文件的方法。分享给大家供大家参考。具体如下:

该程序支持ftp上传下载文件和目录、适用于windows和linux平台。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import ftplib

import os

import sys

class FTPSync(object):

  conn = ftplib.FTP()

  def __init__(self,host,port=21):    

    self.conn.connect(host,port)    

  def login(self,username,password):

    self.conn.login(username,password)

    self.conn.set_pasv(False)

    print self.conn.welcome

  def test(self,ftp_path):

    print ftp_path

    print self._is_ftp_dir(ftp_path)

    #print self.conn.nlst(ftp_path)

    #self.conn.retrlines( 'LIST ./a/b')

    #ftp_parent_path = os.path.dirname(ftp_path)

    #ftp_dir_name = os.path.basename(ftp_path)

    #print ftp_parent_path

    #print ftp_dir_name

  def _is_ftp_file(self,ftp_path):

    try:

      if ftp_path in self.conn.nlst(os.path.dirname(ftp_path)):

        return True

      else:

        return False

    except ftplib.error_perm,e:

      return False

  def _ftp_list(self, line):

    list = line.split(' ')

    if self.ftp_dir_name==list[-1] and list[0].startswith('d'):

      self._is_dir = True

  def _is_ftp_dir(self,ftp_path):

    ftp_path = ftp_path.rstrip('/')

    ftp_parent_path = os.path.dirname(ftp_path)

    self.ftp_dir_name = os.path.basename(ftp_path)

    self._is_dir = False

    if ftp_path == '.' or ftp_path== './' or ftp_path=='':

      self._is_dir = True

    else:

      #this ues callback function ,that will change _is_dir value

      try:

        self.conn.retrlines('LIST %s' %ftp_parent_path,self._ftp_list)

      except ftplib.error_perm,e:

        return self._is_dir    

    return self._is_dir

  def get_file(self,ftp_path,local_path='.'):

    ftp_path = ftp_path.rstrip('/')

    if self._is_ftp_file(ftp_path):    

      file_name = os.path.basename(ftp_path)

      #如果本地路径是目录,下载文件到该目录

      if os.path.isdir(local_path):

        file_handler = open(os.path.join(local_path,file_name), 'wb' )

        self.conn.retrbinary("RETR %s" %(ftp_path), file_handler.write) 

        file_handler.close()

      #如果本地路径不是目录,但上层目录存在,则按照本地路径的文件名作为下载的文件名称

      elif os.path.isdir(os.path.dirname(local_path)):

        file_handler = open(local_path, 'wb' )

        self.conn.retrbinary("RETR %s" %(ftp_path), file_handler.write) 

        file_handler.close()

      #如果本地路径不是目录,且上层目录不存在,则退出

      else:

        print 'EROOR:The dir:%s is not exist' %os.path.dirname(local_path)

    else:

      print 'EROOR:The ftp file:%s is not exist' %ftp_path

  def put_file(self,local_path,ftp_path='.'):

    ftp_path = ftp_path.rstrip('/')

    if os.path.isfile( local_path ):           

      file_handler = open(local_path, "r")

      local_file_name = os.path.basename(local_path)

      #如果远程路径是个目录,则上传文件到这个目录,文件名不变

      if self._is_ftp_dir(ftp_path):

        self.conn.storbinary('STOR %s'%os.path.join(ftp_path,local_file_name), file_handler)

      #如果远程路径的上层是个目录,则上传文件,文件名按照给定命名

      elif self._is_ftp_dir(os.path.dirname(ftp_path)): 

        print 'STOR %s'%ftp_path        

        self.conn.storbinary('STOR %s'%ftp_path, file_handler)

      #如果远程路径不是目录,且上一层的目录也不存在,则提示给定远程路径错误

      else:        

        print 'EROOR:The ftp path:%s is error' %ftp_path

      file_handler.close()

    else:

      print 'ERROR:The file:%s is not exist' %local_path

  def get_dir(self,ftp_path,local_path='.',begin=True): 

    ftp_path = ftp_path.rstrip('/')

    #当ftp目录存在时下载    

    if self._is_ftp_dir(ftp_path):

      #如果下载到本地当前目录下,并创建目录

      #下载初始化:如果给定的本地路径不存在需要创建,同时将ftp的目录存放在给定的本地目录下。

      #ftp目录下文件存放的路径为local_path=local_path+os.path.basename(ftp_path)

      #例如:将ftp文件夹a下载到本地的a/b目录下,则ftp的a目录下的文件将下载到本地的a/b/a目录下

      if begin:

        if not os.path.isdir(local_path):

          os.makedirs(local_path)

        local_path=os.path.join(local_path,os.path.basename(ftp_path))

      #如果本地目录不存在,则创建目录

      if not os.path.isdir(local_path):

        os.makedirs(local_path)

      #进入ftp目录,开始递归查询

      self.conn.cwd(ftp_path)

      ftp_files = self.conn.nlst()

      for file in ftp_files:

        local_file = os.path.join(local_path, file)

        #如果file ftp路径是目录则递归上传目录(不需要再进行初始化begin的标志修改为False)

        #如果file ftp路径是文件则直接上传文件

        if self._is_ftp_dir(file):

          self.get_dir(file,local_file,False)

        else:

          self.get_file(file,local_file)

      #如果当前ftp目录文件已经遍历完毕返回上一层目录

      self.conn.cwd( ".." )

      return

    else:

      print 'ERROR:The dir:%s is not exist' %ftp_path

      return

  def put_dir(self,local_path,ftp_path='.',begin=True):

    ftp_path = ftp_path.rstrip('/')

    #当本地目录存在时上传

    if os.path.isdir(local_path):      

      #上传初始化:如果给定的ftp路径不存在需要创建,同时将本地的目录存放在给定的ftp目录下。

      #本地目录下文件存放的路径为ftp_path=ftp_path+os.path.basename(local_path)

      #例如:将本地文件夹a上传到ftp的a/b目录下,则本地a目录下的文件将上传的ftp的a/b/a目录下

      if begin:        

        if not self._is_ftp_dir(ftp_path):

          self.conn.mkd(ftp_path)

        ftp_path=os.path.join(ftp_path,os.path.basename(local_path))          

      #如果ftp路径不是目录,则创建目录

      if not self._is_ftp_dir(ftp_path):

        self.conn.mkd(ftp_path)

      #进入本地目录,开始递归查询

      os.chdir(local_path)

      local_files = os.listdir('.')

      for file in local_files:

        #如果file本地路径是目录则递归上传目录(不需要再进行初始化begin的标志修改为False)

        #如果file本地路径是文件则直接上传文件

        if os.path.isdir(file):          

          ftp_path=os.path.join(ftp_path,file)

          self.put_dir(file,ftp_path,False)

        else:

          self.put_file(file,ftp_path)

      #如果当前本地目录文件已经遍历完毕返回上一层目录

      os.chdir( ".." )

    else:

      print 'ERROR:The dir:%s is not exist' %local_path

      return

if __name__ == '__main__':

  ftp = FTPSync('192.168.1.110')

  ftp.login('test','test')

  #上传文件,不重命名

  #ftp.put_file('111.txt','a/b')

  #上传文件,重命名

  #ftp.put_file('111.txt','a/112.txt')

  #下载文件,不重命名

  #ftp.get_file('/a/111.txt',r'D:\\')

  #下载文件,重命名

  #ftp.get_file('/a/111.txt',r'D:\112.txt')

  #下载到已经存在的文件夹

  #ftp.get_dir('a/b/c',r'D:\\a')

  #下载到不存在的文件夹

  #ftp.get_dir('a/b/c',r'D:\\aa')

  #上传到已经存在的文件夹

  ftp.put_dir('b','a')

  #上传到不存在的文件夹

  ftp.put_dir('b','aa/B/')

希望本文所述对大家的Python程序设计有所帮助。

以下转自:http://blog.csdn.net/linda1000/article/details/8255771

Python中的ftplib模块

Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件

FTP的工作流程及基本操作可参考协议RFC959

ftp登陆连接

from ftplib import FTP #加载ftp模块

ftp=FTP() #设置变量

ftp.set_debuglevel(2) #打开调试级别2,显示详细信息

ftp.connect("IP","port") #连接的ftp sever和端口

ftp.login("user","password")#连接的用户名,密码

print ftp.getwelcome() #打印出欢迎信息

ftp.cmd("xxx/xxx") #更改远程目录

bufsize=1024 #设置的缓冲区大小

filename="filename.txt" #需要下载的文件

file_handle=open(filename,"wb").write #以写模式在本地打开文件

ftp.retrbinaly("RETR filename.txt",file_handle,bufsize) #接收服务器上文件并写入本地文件

ftp.set_debuglevel(0) #关闭调试模式

ftp.quit #退出ftp

ftp相关命令操作

ftp.cwd(pathname) #设置FTP当前操作的路径

ftp.dir() #显示目录下文件信息

ftp.nlst() #获取目录下的文件

ftp.mkd(pathname) #新建远程目录

ftp.pwd() #返回当前所在位置

ftp.rmd(dirname) #删除远程目录

ftp.delete(filename) #删除远程文件

ftp.rename(fromname, toname)#将fromname修改名称为toname。

ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #上传目标文件

ftp.retrbinary("RETR filename.txt",file_handel,bufsize)#下载FTP文件

网上找到一个具体的例子:

# 例:FTP编程  

from ftplib import FTP  

      

ftp = FTP()  

timeout = 30  

port = 21  

ftp.connect('192.168.1.188',port,timeout) # 连接FTP服务器  

ftp.login('UserName','888888') # 登录  

print ftp.getwelcome()  # 获得欢迎信息   

ftp.cwd('file/test')    # 设置FTP路径  

list = ftp.nlst()       # 获得目录列表  

for name in list:  

    print(name)             # 打印文件名字  

path = 'd:/data/' + name    # 文件保存路径  

f = open(path,'wb')         # 打开要保存文件  

filename = 'RETR ' + name   # 保存FTP文件  

ftp.retrbinary(filename,f.write) # 保存FTP上的文件  

ftp.delete(name)            # 删除FTP文件  

ftp.storbinary('STOR '+filename, open(path, 'rb')) # 上传FTP文件  

ftp.quit()                  # 退出FTP服务器

完整的模板:

#!/usr/bin/python  

# -*- coding: utf-8 -*-  

import ftplib  

import os  

import socket  

  

HOST = 'ftp.mozilla.org'  

DIRN = 'pub/mozilla.org/webtools'  

FILE = 'bugzilla-3.6.7.tar.gz'  

def main():  

    try:  

        f = ftplib.FTP(HOST)  

    except (socket.error, socket.gaierror):  

        print 'ERROR:cannot reach " %s"' % HOST  

        return  

    print '***Connected to host "%s"' % HOST  

  

    try:  

        f.login()  

    except ftplib.error_perm:  

        print 'ERROR: cannot login anonymously'  

        f.quit()  

        return  

    print '*** Logged in as "anonymously"'  

    try:  

        f.cwd(DIRN)  

    except ftplib.error_perm:  

        print 'ERRORL cannot CD to "%s"' % DIRN  

        f.quit()  

        return  

    print '*** Changed to "%s" folder' % DIRN  

    try:  

        #传一个回调函数给retrbinary() 它在每接收一个二进制数据时都会被调用  

        f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)  

    except ftplib.error_perm:  

        print 'ERROR: cannot read file "%s"' % FILE  

        os.unlink(FILE)  

    else:  

        print '*** Downloaded "%s" to CWD' % FILE  

    f.quit()  

    return  

  

if __name__ == '__main__':  

    main()

使用python源文件的几种方法\运行python脚本:

a. windows下打开shell(DOS提示符,命令行,cmd):

CMD命令进入某个目录

如在window 下cmd运行python源文件 xxx.py(注意这个xxx.py在C盘的python27目录下,若是其它盘的目录,就进入其它盘的目录来运行xxx.py):

打开cmd

输入c: 回车

输入cd c:/python27/ 回车 (ps:cd后面没有冒号!,如果需要在dos下查看带有空格的文件夹,要给文件夹加上引号如:CD "Program Files"/PHP )

输入python xxx.py 或者 xxx.py 回车

这是在找到文件路径下去执行某文件,直接在cmd,python环境下输入python xxx.py 会运行语法错误,不知是否是系统的环境变量没有添加好?

在linux下参见vamei :python 基础

另附:cmd命令

1.进入上一层目录 CD ../

2.显示目录下的文件及了目录 dir

b.Linux下运行python源文件:

$ python xxx.py

c.在IDLE下运行python源文件

点击开始->程序->Python 2.7->IDLE(Python GUI)

点击file->open->xxx.py

ctrl+F5

quit()是退出程序

d.在IDLE里,可以通过os执行系统命令,执行python源文件:

import os

os.system('python c:/xxx.py')

e. 直接双击xxx.py

双击xxx.py,窗口一闪而过。很像VC运行时的Ctrl+F5对不对?那怎么办呢?(非windows系统可以跳过,不用此技巧)

这里我们在代码里加入一句话raw_input(),就可以。

在有些情况下,你要测试文件是否存在于远程Linux服务器的某个目录下(例如:/var/run/test_daemon.pid),而无需登录到远程服务器进行交互。例如,你可能希望你的脚本根据特定文件是否存在的远程服务器上而由不同的行为。

在本教程中,我将向您展示如何使用不同的脚本语言(如:Bash shell,Perl,Python)查看远程文件是否存在。

这里描述的方法将使用ssh访问远程主机。您首先需要启用无密码的ssh登录到远程主机,这样您的脚本可以在非交互式的批处理模式访问远程主机。您还需要确保ssh登录文件有读权限检查。假设你已经完成了这两个步骤,您可以编写脚本就像下面的例子

使用bash判断文件是否存在于远程服务器上

#!/bin/bash

ssh_host="xmodulo@remote_server"

file="/var/run/test.pid"

if ssh $ssh_host test -e $file

then echo $file exists

else echo $file does not exist

fi

使用perl判断文件是否存在于远程服务器上

#!/usr/bin/perl

my $ssh_host = "xmodulo@remote_server"

my $file = "/var/run/test.pid"

system "ssh", $ssh_host, "test", "-e", $file

my $rc = $? >>8

if ($rc) {

print "$file doesn't exist\n"

} else {

print "$file exists\n"

}

使用python判断文件是否存在于远程服务器上

#!/usr/bin/python

import subprocess

import pipes

ssh_host = 'xmodulo@remote_server'

file = '/var/run/test.pid'

resp = subprocess.call(

['ssh', ssh_host, 'test -e ' + pipes.quote(file)])

if resp == 0:

print ('%s exists' % file)

else:

print ('%s does not exist' % file)