美文网首页Python
python--ftp推送文件

python--ftp推送文件

作者: w_dll | 来源:发表于2021-04-22 08:27 被阅读0次

利用python的ftp模块, 批处理推送文件
主要是为windows服务器,linux还是scp更加方便
目前只写了mput上传模块,下载模块如果后面有需求在写
根据这个脚本稍微改进了下
https://blog.csdn.net/qq_26775359/article/details/93500728

#-*- coding:utf-8 -*-
from ftplib import FTP
import socket, time, os

class MyFtp():
  def __init__(self, **kwargs):
    remote_ip = kwargs.get('remote_host', None)
    user      = kwargs.get('user', None)
    passwd    = kwargs.get('passwd', None)
    port      = kwargs.get('remote_port', '21')
    base_dir  = kwargs.get('base_dir', None)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    self.tag  = s.getsockname()[0]
    #self.tag  = socket.gethostbyname(socket.gethostname())
    self.ftp  = FTP()
    #self.ftp.set_debuglevel(2)
    self.ftp.connect(remote_ip, port)
    self.ftp.login(user, passwd)
    if base_dir != None:
      self.ftp.cwd(base_dir)

  def split_path(self, path):
    res = os.path.split(path)
    t_path_list = []
    while res[1]:
      t_path_list.append(res[1])
      res = os.path.split(res[0])
    path_list = []
    path_list.append(res[0])
    while t_path_list:
      path_list.append(t_path_list.pop())
    return path_list

  def is_same_size(self, local_file, remote_file):
    try:
      remote_file_size = self.ftp.size(remote_file)
    except Exception, err:
      remote_file_size = -1

    try:
      local_file_size = os.path.getsize(local_file)
    except Exception, err:
      local_file_size = -1
    print('local_file_size:%d, remote_file_size:%d' % (local_file_size, remote_file_size))
    if remote_file_size == local_file_size:
      return 1
    else:
      return 0

  def upload_file(self, local_file, **kwargs):
    remote_dir  = kwargs.get('remote_dir', None)
    remote_file = kwargs.get('remote_file', None)
    tag         = kwargs.get('tag', None)
    if remote_dir != None:
      self.ftp.cwd(remote_dir)
    if not os.path.isfile(local_file):
      print('local file ==> %s not found!' % local_file)
      return
    if self.is_same_size(local_file, remote_file):
      print('local file ==> %s pass' % local_file)
      return
    if remote_file == None:
      file_name = os.path.split(local_file)[-1]
      if tag == 'ip':
        remote_file = str(self.tag) + '-' +  file_name
      else:
        remote_file = file_name
    buf_size = 1024
    file_handler = open(local_file, 'rb')
    self.ftp.storbinary('STOR %s' % remote_file, file_handler, buf_size)
    file_handler.close()
    print('upload file ==> %s' % local_file)

  def upload_file_tree(self, local_path, **kwargs):
    tag         = kwargs.get('tag', None)
    remote_path = kwargs.get('remote_path', os.path.split(local_path)[-1])
    print("tag ==> %s" % tag)
    if tag == 'ip':
      remote_path = str(self.tag) + '-' + remote_path

    if not os.path.isdir(local_path):
      print('local path -==> %s not found!' % local_path)
      return
    try:
      self.ftp.cwd(remote_path)
    except Exception, e:
      dir_list = self.split_path(remote_path)
      for i in dir_list:
        try:
          self.ftp.cwd(i)
        except Exception, e:
          #print('INFO: %s' %  e)
          self.ftp.mkd(i)
          self.ftp.cwd(i)
    print('ftp server path ==> %s' % self.ftp.pwd())

    local_name_list = os.listdir(local_path)
    for local_name in local_name_list:
      src = os.path.join(local_path, local_name)
      print("sub dir ==> %s" % src)
      if os.path.isdir(src):
        try:
          self.ftp.mkd(local_name)
        except Exception ,err:
          print("remote path ==> %s, pass" % local_name)
        print("full path ==> %s sub path ==> %s" % (local_name, src))
        remote_dir = os.path.join(self.ftp.pwd(), local_name)
        self.upload_file_tree(src, remote_path=remote_dir)
      else:
        print("upload file ==> %s" % local_name)
        self.upload_file(src)
    self.ftp.cwd('..')

  def mput(self, src, **kwargs):
    if os.path.isfile(src):
      self.upload_file(src, **kwargs)
    elif os.path.isdir(src):
      self.upload_file_tree(src, **kwargs)

  def close(self):
    self.ftp.quit()


def get_file_list(base_dir, tag):
  file_list = []
  if os.path.isdir(base_dir):
    print("dir == > %s" % base_dir)
    os.chdir(base_dir)
    res = os.listdir(base_dir)
    for i in res:
      if tag in i:
        file_list.append(i)
    return file_list

if __name__ == '__main__':
  file_list = get_file_list(base_dir, tag)
  ftp_cfg = { 'user':'root', \
         'remote_host':'192.168.191.250', \
         'passwd':'Kk5s%2^nDUi9', \
         'remote_port':'21',
         'base_dir':'/home/wq/FTP_DIR'
        }
  myftp = MyFtp(**ftp_cfg)
  for i in file_list:
    myftp.mput(i, tag='ip')
  myftp.close()

执行结果



ftp 服务端查看


相关文章

网友评论

    本文标题:python--ftp推送文件

    本文链接:https://www.haomeiwen.com/subject/phhxrltx.html