ftp协议拉去远程文件,并且传送到远端(python)

main.py

# 这是一个示例 Python 脚本。
# -*- coding: UTF-8 -*-

from ftplib import FTP
import os
import datetime
import sys
import file_op


class FTP_OP(object):
    def __init__(self, host, username, password, port):
        """
        初始化ftp
      :param host: ftp主机ip
      :param username: ftp用户名
      :param password: ftp密码
      :param port: ftp端口 (默认21)
      """
        self.host = host
        self.username = username
        self.password = password
        self.port = port

    def ftp_connect(self):
        """
        连接ftp
        :return:
        """
        ftp = FTP()
        ftp.set_debuglevel(1)  # 不开启调试模式
        ftp.connect(host=self.host, port=self.port)  # 连接ftp
        ftp.login(self.username, self.password)  # 登录ftp
        ftp.encoding="gbk"
        ftp.set_pasv(True)  ##ftp有主动 被动模式 需要调整
        return ftp

    def download_file(self, ftp_file_path, dst_file_path, prefix):
        """
        从ftp下载文件到本地
        :param ftp_file_path: ftp下载文件路径
        :param dst_file_path: 本地存放路径
        :return:
        """
        buffer_size = 102400  # 默认是8192
        ftp = self.ftp_connect()
        print(ftp.getwelcome())  # 显示登录ftp信息
        file_list = ftp.nlst(ftp_file_path)
        file_list_to_sort = []
        res = None
        print("prefix = ",prefix)
        for file_name in file_list:
            if file_name.startswith(prefix):        #判断文件名中是否是以指定字符(prefix)开头
                file_list_to_sort.append(file_name)
        file_list_to_sort.sort()
        if not os.path.exists(dst_file_path):       #如果没有该文件则创建一个
            os.makedirs(dst_file_path)
        if len(file_list_to_sort) > 0:
            if not os.path.exists(os.path.abspath(dst_file_path + file_list_to_sort[-1])):      #取文件列表的最后一个文件的绝对路径
                write_file = dst_file_path + file_list_to_sort[-1]
                ftp_file = os.path.join(ftp_file_path, file_list_to_sort[-1])
                with open(write_file, "wb") as f:
                    ftp.retrbinary('RETR %s' % ftp_file, f.write, buffer_size)
                print("download file_name:" + file_list_to_sort[-1])
            else:
                print("file_name exist, name:" + file_list_to_sort[-1])
            res = file_list_to_sort[-1]
        ftp.quit()
        return res

# require linux authentication key; Windows net share
if __name__ == '__main__':
    host = "127.0.0.1"
    username = "anonymous"
    password = ""
    port = 21
    method = 1
    if (len(sys.argv) > 2):
        if sys.argv[2] in ("1", "2", "3"):
            method = int(sys.argv[2])
    print(method)
    ftp = FTP_OP(host=host, username=username, password=password, port=port)
    if method == 1 or method == 3:
        print("in 1")
        wind_ftp_file_path = "/"          # ftp目录
        wind_dst_file_path = "../files/"  # 本地目录

        # file_op.resetDir(wind_dst_file_path)
        latest_server_file = ftp.download_file(ftp_file_path=wind_ftp_file_path, dst_file_path=wind_dst_file_path,
                                        prefix="pc_windows_" + datetime.datetime.now().strftime('%m%d'))
        latest_client_file = ftp.download_file(ftp_file_path=wind_ftp_file_path, dst_file_path=wind_dst_file_path,
                                        prefix="pc_Windows_" + datetime.datetime.now().strftime('%m%d'))
        latest_file = "pc_Windows_1229_1357_svn12418_Mario_MultiServer.rar"
        if latest_server_file:
            print("********************************\n" + "latest_server_file : " + latest_server_file)
            abs_path = os.path.abspath(wind_dst_file_path + latest_server_file)
            print(abs_path)
            file_op.upload_to_winds(abs_path)

    if method == 2 or method == 3:
        print("in 2")
        linux_ftp_file_path = "/"                   #
        linux_dst_file_path = "../linux_files/"

        # file_op.resetDir(linux_dst_file_path)
        latest_file = ftp.download_file(ftp_file_path=linux_ftp_file_path, dst_file_path=linux_dst_file_path,
                                        prefix="pc_linux_" + datetime.datetime.now().strftime('%m%d'))
        if latest_file:
            print("********************************\n" + "latest_file_name : " + latest_file)
            abs_path = os.path.abspath(linux_dst_file_path + latest_file)
            print(abs_path)
            file_op.upload_to_linux(abs_path)

main.py主要是拉去远端的文件的到本地

file_op.py

import shutil
import os

def resetDir(filepath):
    if not os.path.exists(filepath):
        os.mkdir(filepath)
    else:
        shutil.rmtree(filepath)
        os.mkdir(filepath)

def upload_to_winds(filename):
    destIp = "127.0.0.1"        #目标ip,这里是我随意写的ip
    path_name = "Path"   # net
    user_pwd = "123456"
    user_account = "shared"
    logincmd = "net use \\\\" + destIp + "\\" + path_name + " "+user_pwd+" /user:"+user_account
    print("cmd: "+logincmd)
    resLog = os.popen(logincmd, 'r', 1).read()
    print(resLog)
    destpath = "files\\"
    xcpycmd = "xcopy " + filename + " \\\\" + destIp + "\\" + path_name + "\\" + destpath + " /s /y"
    print("cmd: " + xcpycmd)
    resLog = os.popen(xcpycmd, 'r', 1).read()
    print(resLog)

def upload_to_linux(filename):
    destIp = "127.0.0.1"
    destpath = "/home/workspace/" 
    user_account = "root"   # 需加authentication key
    scpycmd = "scp " + filename + " " + user_account + "@" + destIp + ":" + destpath
    print("cmd: " + scpycmd)
    resLog = os.popen(scpycmd, 'r', 1).read()
    print(resLog)

file_op.py是对拉去到本地的文件传送到远端,使用的是net

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值