#!/usr/bin/python
# -*- coding: UTF-8 -*-
from ftplib import FTP
import os
import sys
import datetime
import time
import socket
import shutil
class MyFTP:
"""
ftp自动下载、自动上传脚本,支持单文件上传
author:王宽
"""
def __init__(self, host, port=21):
""" 初始化 FTP 客户端
参数:
host:ip地址
port:端口号
"""
# print("__init__()---> host = %s ,port = %s" % (host, port))
self.host = host
self.port = port
self.ftp = FTP()
# 重新设置下编码方式
self.ftp.encoding = 'gbk'
#self.log_file = open("/app/interrate_report/log/ftp_log.%s"%current_date, "a")
#self.file_list = []
def login(self, username, password):
""" 初始化 FTP 客户端
参数:
username: 用户名
password: 密码
"""
try:
timeout = 60
socket.setdefaulttimeout(timeout)
# 0主动模式 1 #被动模式
self.ftp.set_pasv(True)
# 打开调试级别2,显示详细信息
# self.ftp.set_debuglevel(2)
print('开始尝试连接到 %s' % self.host)
self.ftp.connect(self.host, self.port)
print('成功连接到 %s' % self.host)
print('开始尝试登录到 %s' % self.host)
self.ftp.login(username, password)
print('成功登录到 %s' % self.host)
print(self.ftp.welcome)
except Exception as err:
print("FTP 连接或登录失败 ,错误描述为:%s" % err)
pass
def upload_file(self, local_file, file_name,remote_path):
"""从本地上传文件到ftp
参数:
local_path: 本地文件
remote_path: 远程文件
"""
if not os.path.isfile(local_file):
print('%s 不存在' % local_file)
return
# 设置FTP当前操作路径
self.ftp.cwd(remote_path)
print('切换至远程目录: %s' % remote_path)
buf_size = 1024
file_handler = open(local_file, 'rb')
self.ftp.storbinary('STOR %s' % file_name, file_handler, buf_size)
file_handler.close()
print('上传: %s' % local_file + "成功!")
def close(self):
""" 退出ftp
"""
print("close()---> FTP退出")
self.ftp.quit()
if __name__ == "__main__":
my_ftp = MyFTP("XXXX")
my_ftp.login("administrator", "XXXXX")
# 设置本地待推送文件名,每次调用前修改
local_file = "/app/interrate_report/tmp/20210624/20210624/imas_check_result_1_20210624.csv"
# 目标端文件名
remote_file = "imas_check_result_1_20210624.csv"
# 本地文件 待上传远端路径,每次调用前修改
remote_path = "/report/20210624"
# 上传文件
my_ftp.upload_file(local_file,remote_file,remote_path)
# 关闭ftp
my_ftp.close()
Python每日练习之ftp文件上传
最新推荐文章于 2024-05-26 23:53:19 发布
1313

被折叠的 条评论
为什么被折叠?



