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文件
__author__ = 'Administrator'
import sys,os,ftplib,socket
import jiexiliuhui
CONST_BUFFER_SIZE = 81920
filepath = '/root/water'
def connect(CONST_HOST = "xxx.xxx.xxx.xxx"):
CONST_USERNAME = "root"
CONST_PWD = "mima"
try:
ftp = ftplib.FTP(CONST_HOST)
ftp.login(CONST_USERNAME,CONST_PWD)
return ftp
except (socket.error,socket.gaierror):
print("FTP 链接失败,请检查主机是否正常")
sys.exit(0)
def disconnect(ftp):
ftp.quit()
def upload(ftp, filepath):
f = open(filepath, "rb")
file_name = os.path.split(filepath)[-1]
try:
ftp.storbinary('STOR %s'%file_name, f, CONST_BUFFER_SIZE)
except ftplib.error_perm:
return False
return True
def download(ftp, filename):
f = open(filename,"wb").write
try:
ftp.retrbinary("RETR %s"%filename, f, CONST_BUFFER_SIZE)
except ftplib.error_perm:
return False
return True
def list(ftp):
ftp.dir()
def find(ftp,filename):
ftp_f_list = ftp.nlst()
if filename in ftp_f_list:
return True
else:
return False
def main():
CONST_HOST = input("网关IP地址:")
ftp = connect(CONST_HOST)
ftp.cwd(filepath)
flist = ftp.nlst(filepath)
diclist = {}
print(CONST_HOST," 的流水有:")
for index,filename in enumerate(flist):
diclist[index] = filename[-8:]
print(diclist)
selectNum = input("请选择文件:")
try:
selectNum = int(selectNum)
except :
print("请输入合法数字")
if selectNum>= len(diclist):
print("请输入有效数字")
if download(ftp,diclist[selectNum]):
print("下载文件", diclist[selectNum],"成功")
else:
print("下载文件", diclist[1],"失败")
disconnect(ftp)
#调用自编函数解析文件并声称excel
jiexiliuhui.jiexiliushui(diclist[selectNum])
if __name__ == "__main__":
main()
content = input("")
if (content != ""):
exit
jiexiliuhui.py
__author__ = 'Administrator'
def jiexiliushui(filename):
"""
:param filename: 待解析的文件名
:return:
"""
import time
import xlwt
f = open(filename,'rb')
f.seek(0,0)
index = 0
# for i in range(0,16):
# print("%-9s"%i, end='')
# print('')
#path = input("保存的EXCEL名:")
path = ''
if path =="":
path = time.strftime("%Y%m%d%H%M%S", time.localtime())+'.xls'
else:
if path[-4:] != '.xls':
path = path+'.xls'
wb=xlwt.Workbook()
sheet1 = wb.add_sheet("liushui")
value = ["流水号","表号","度数","功率","时间"]
for i in range(0,5):
sheet1.write(0,i,value[i])
ncols = 0
while True:
temp=f.read(32)
if len(temp) < 32:
wb.save(path)
break
else:
ncols = ncols+1
liushuihao = temp[3]*256**3 + temp[2]*256**2 + temp[1]*256 + temp[0]*256**0
caijishijian = str(temp[5])+"-"+str(temp[6]).zfill(2)+"-"+str(temp[7]).zfill(2)+" "+str(temp[8]).zfill(2)+":"+str(temp[9]).zfill(2)+":"+str(temp[10]).zfill(2)
biaohao = str(hex(temp[16]))[2:].zfill(2)+str(hex(temp[15]))[2:].zfill(2)+str(hex(temp[14]))[2:].zfill(2)+str(hex(temp[13]))[2:].zfill(2)+str(hex(temp[12]))[2:].zfill(2)+str(hex(temp[11]))[2:].zfill(2)
if biaohao.isdigit():
biaohao = int(biaohao)
if str(hex(temp[18])) == '0xff':
dushuo = -1
gonglv = -1
else:
dushuo = int(str(hex(temp[21]))[2:].zfill(2)+str(hex(temp[20]))[2:].zfill(2)+str(hex(temp[19]))[2:].zfill(2)+str(hex(temp[18]))[2:].zfill(2))*0.01
if str(hex(temp[24])) == '0xff':
gonglv = -1
else:
gonglv = int(str(hex(temp[24]))[2:].zfill(2)+str(hex(temp[23]))[2:].zfill(2)+str(hex(temp[22]))[2:].zfill(2))*0.0001
# print("流水号:%d;表号:%d;度数:%8.2f;功率:%6.4f;时间:%s" %(liushuihao,biaohao,dushuo,gonglv,caijishijian))
value = [liushuihao,biaohao,dushuo,gonglv,caijishijian]
for i, each in enumerate(value):
sheet1.write(ncols,i,each)
f.close()
def modeName():
return __name__