This commit is contained in:
gqh
2023-01-09 23:04:53 +08:00
parent d0497aa043
commit 311c7c723a
52 changed files with 1572 additions and 331 deletions

View File

@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
import os
from ftplib import FTP
class FTP_P(FTP):
def dirs(self, *args):
'''List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command. (This *should* only be used for a pathname.)'''
cmd = 'LIST'
templist = []
tempdic = {}
func = None
if args[-1:] and type(args[-1]) != type(''):
args, func = args[:-1], args[-1]
for arg in args:
if arg:
cmd = cmd + (' ' + arg)
self.retrlines(cmd, templist.append)
# print(templist)
# 处理返回结果,只需要目录名称
r_files = [file.split(" ")[-1] for file in templist]
tempdic['name'] = [file for file in r_files if file != "." and file != ".."]
# 去除. ..
return tempdic
# return [file for file in r_files if file != "." and file != ".."]
# FTP接口类
class FtpController():
'''
这是ftp接口类在类初始化的时候就连接了ftp服务器能否成功连接有反馈。
类中定义了两个接口:上传接口和删除接口
'''
# 三菱机床连接
def __init__(self, host="192.168.2.158", port=8080, username="MITSUBISHI", password="CNC"):
self.host = host
self.port = port
self.username = username
self.password = password
ftp = FTP_P()
# self.ftp.set_debuglevel(2) #打开调试级别2显示详细信息
ftp.set_pasv(0) #0主动模式 1 #被动模式
try:
ftp.connect(self.host, self.port)
ftp.login(self.username, self.password)
print("连接成功")
self.ftp = ftp
except:
print("连接失败")
# 试验接口
def prin(self):
print("这是试验接口")
# 试验ftp服务器连接
# def connect(self, host="127.0.0.1", port=2121, username="admin", password="123456"):
# ftp = FTP_P()
# try:
# ftp.connect(host, port)
# ftp.login(username, password)
# print("连接成功")
# ftp1 = ftp
# return ftp1
# except:
# print("连接失败")
# 三菱代码下发
def upload_file(self, remotepath='/(192,168,199,2)/DS/Z4.5.NC', localpath='D:/ftp/up/Z4.5.NC'):
'''
第一个是要上传到ftp服务器路径下的文件第二个是本地要上传的的路径文件
:param remotepath: 上传和下载都需要设置工作目录,注意只能使用文件名,不能有路径中的冒号
:param localpath:
:return:
'''
bufsize = 1024
fp = open(localpath, 'rb')
self.ftp.storbinary('STOR ' + remotepath, fp, bufsize)
fp.close()
# return "上传成功"
def delAllfile(self, ftppath):
dir_res = []
try:
print(ftppath)
try:
self.ftp.cwd(ftppath)
except Exception as e:
print("进入ftp目录失败" + str(e))
self.ftp.dir('.', dir_res.append) # 对当前目录进行dir(),将结果放入列表
print(dir_res)
# for i in dir_res:
# if i.startswith("d"):
# dirName = i.split(" ")[-1]
# print("开始删除" + dirName + "文件夹")
# delAllfile(ftp, ftp.pwd() + "/" + dirName)
# ftp.cwd('..')
# print(ftppath + "/" + dirName)
# ftp.rmd(ftppath + '/' + dirName)
# else:
# filelist = ftp.getfiles(ftppath)
# for f in filelist:
# print("删除FTP目录" + ftppath + "下存在文件:" + f)
# ftp.delete(f)
except Exception as e:
raise e
# 删除远端ftp文件
# 出现550 not found file是路径不对
# def del_file(self, delpath='./YIN.NC'):
def del_file(self, delpath='/(192,168,199,2)/DS/Z4.5.NC'):
self.ftp.delete(delpath) # 删除远程文件