当前位置:   article > 正文

十八.Python模拟FTP文件上传_python 模拟 filezilla上传文件

python 模拟 filezilla上传文件

Python 模拟FTP断点续传并发服务器

 

#配置文件

#服务器配置文件

  1. [server_config]
  2. ip=127.0.0.1
  3. port=8006
  4. buffersize=1024
  5. encoding=utf-8

#服务器用户数据 

  1. [tom]
  2. username=tom
  3. password=123456
  4. [alex]
  5. username=alex
  6. password=123456

 

#FTP服务器代码

  1. #程序入口
  2. import optparse
  3. import sys,os
  4. #os.path.dirname 获取文件的文件夹路径
  5. path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  6. sys.path.append(path)
  7. from core import main
  8. class ftt_server:
  9. def __init__(self):
  10. self.option = optparse.OptionParser()
  11. self.option.add_option("-i", "--ip", dest="ip")
  12. self.option.add_option("-p", "--port", dest="port")
  13. self.opt, self.args = self.option.parse_args()
  14. self.one()
  15. def one(self):
  16. main.main(self.opt, self.args)
  17. if __name__=="__main__":
  18. ftt_server()
  1. #服务器监听程序
  2. import socketserver
  3. import optparse
  4. import configparser
  5. import os
  6. from core import server
  7. class main():
  8. def __init__(self,opt,args):
  9. args=args
  10. self.option=opt
  11. self.config=configparser.ConfigParser()
  12. self.config.read(os.path.dirname(os.path.dirname(__file__))+"/conf/config.ini")
  13. self.server=server
  14. self.BaseDir=os.path.dirname(os.path.dirname(__file__))
  15. self.validate(opt, args)
  16. def validate(self, options, args):
  17. cmd=args[0]
  18. if hasattr(self,cmd):
  19. fun=getattr(self,cmd)
  20. fun()
  21. def start(self):
  22. ip=self.option.ip
  23. port=self.option.port
  24. if ip=="":
  25. ip=self.getConfig("server_config","ip")
  26. if port=="":
  27. port=self.getConfig("server_config","port")
  28. print("server start Successful!")
  29. self.sock_ser=socketserver.ThreadingTCPServer((ip,int(port)),self.server.server_handler)
  30. self.sock_ser.serve_forever()
  31. def help(self):
  32. pass
  33. def getConfig(self,section,attribute):
  34. return self.config.read(section,attribute)
  1. #服务器主程序
  2. import socketserver
  3. import configparser
  4. import os
  5. import json
  6. import sys
  7. class server_handler(socketserver.BaseRequestHandler):
  8. def handle(self):
  9. self.config_name="server_config"
  10. self.BaseDir=os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
  11. self.config_Path=os.path.join(self.BaseDir,"conf","config.ini")
  12. self.user_config=os.path.join(self.BaseDir,"conf","user.ini")
  13. self.buffersize=int(self.getIni(self.config_Path,self.config_name,"buffersize"))
  14. self.encoding=self.getIni(self.config_Path,self.config_name,"encoding")
  15. self.currenSize=0
  16. data = self.request.recv(self.buffersize).decode(self.encoding)
  17. data = json.loads(data)
  18. print(data)
  19. fun = data["action"]
  20. if fun=="login":
  21. con=configparser.ConfigParser()
  22. con.read(self.user_config)
  23. if con.has_section(data["user"]):
  24. if con.get(data["user"],"password")==data["password"]:
  25. self.currenDir=data["user"]
  26. self.request.sendall("504".encode("utf-8"))
  27. self.name=data["user"]
  28. self.home=os.path.join(self.BaseDir, "home",data["user"])
  29. self.currenDir=self.home
  30. self.interception()
  31. else:
  32. self.request.sendall("404".encode("utf-8"))
  33. def getIni(self,path,section,attribute):
  34. conf = configparser.ConfigParser()
  35. conf.read(path)
  36. return conf.get(section, attribute)
  37. #交互
  38. def interception(self):
  39. while 1:
  40. print("wait recv....")
  41. data=self.request.recv(self.buffersize)
  42. data=json.loads(data)
  43. print(data)
  44. fun=data["action"]
  45. if hasattr(self,fun):
  46. func=getattr(self,fun)
  47. func(**data)
  48. else:
  49. self.request.sendall("400".encode("utf-8"))
  50. #cd文件夹切换功能
  51. def cd(self,**kwargs):
  52. position=kwargs["position"]
  53. if position=="../":
  54. self.currenDir =os.path.dirname(self.currenDir)
  55. else:
  56. self.currenDir=os.path.join(self.currenDir,position)
  57. self.request.sendall(os.path.basename(self.currenDir).encode(self.encoding))
  58. #创建文件夹功能
  59. def mkdir(self,**kwargs):
  60. print(kwargs)
  61. position=kwargs["position"]
  62. mkfile=os.path.join(self.currenDir,position)
  63. try:
  64. if "/" in position or "\\" in position:
  65. os.makedirs(mkfile)
  66. else:
  67. os.mkdir(mkfile)
  68. except Exception as e:
  69. self.request.sendall("605".encode(self.encoding))
  70. self.request.sendall("606".encode(self.encoding))
  71. #显示当前文件夹内容
  72. def ls(self,**kwargs):
  73. dir_con=os.listdir(self.currenDir)
  74. self.request.sendall(str(dir_con).encode("utf-8"))
  75. #文件断点续传功能
  76. def put(self,**kwargs):
  77. file_name=kwargs["file_name"]
  78. file_size=kwargs["file_size"]
  79. target=kwargs["target"]
  80. self.target_file=os.path.join(self.currenDir,target,file_name)
  81. if os.path.exists(self.target_file):
  82. self.currenSize=os.stat(self.target_file).st_size
  83. if self.currenSize>=file_size:
  84. self.request.sendall("801".encode(self.encoding))
  85. return
  86. else:
  87. self.request.sendall("802".encode(self.encoding))
  88. data=self.request.recv(self.buffersize).decode(self.encoding)
  89. if data=="Y":
  90. f = open(self.target_file, "ab")
  91. self.request.sendall(str(self.currenSize).encode(self.encoding))
  92. else:
  93. f = open(self.target_file, "wb")
  94. else:
  95. f = open(self.target_file, "wb")
  96. self.request.sendall("803".encode("utf-8"))
  97. while self.currenSize<file_size:
  98. data=self.request.recv(self.buffersize)
  99. f.write(data)
  100. self.currenSize+=len(data)
  101. self.progess(self.currenSize, file_size)
  102. #文件上传进度
  103. def progess(self,curren,total):
  104. rate = int(curren / total * 100)
  105. if rate > 0:
  106. st=sys.stdout
  107. st.write("%s%% %s \r\n"%(rate,"*"*rate))
  108. st.flush()
  109. if rate==100:
  110. print("upload finish!")

#FTP客户端

#配置文件

  1. [client_config]
  2. buffer_size=1024

#客户端代码

  1. #FTP客户端程序
  2. from socket import *
  3. import sys,os
  4. import optparse
  5. import json
  6. import configparser
  7. path=os.path.dirname(os.path.dirname(__file__))
  8. sys.path.append(path)
  9. #状态字典
  10. dicts={"504":"登陆成功!",
  11. "404":"用户或者密码有误!登陆失败!",
  12. "400":"Input Error",
  13. "606":"create success",
  14. "605":"create fail",
  15. "801":"the file is existing",
  16. "802":"the file is existing,but not enough",
  17. "803":"the file start upload..."
  18. }
  19. class client_handler:
  20. def __init__(self):
  21. self.option=optparse.OptionParser()
  22. self.option.add_option("-i", "--ip", dest="ip")
  23. self.option.add_option("-p", "--port", dest="port")
  24. self.option.add_option("-u", "--user", dest="username")
  25. self.option.add_option("-P", "--password", dest="password")
  26. self.conf = configparser.ConfigParser()
  27. self.Base_Dir=os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
  28. self.buffersize= int(self.bufferSize())
  29. self.size_file=0
  30. options, args = self.option.parse_args()
  31. self.task(options,args)
  32. def task(self, options, args):
  33. port=options.port
  34. if int(port)>0 and int(port)<65535:
  35. self.make_connection(options,args)
  36. else:
  37. exit("the port is in 0 and 65535!")
  38. def make_connection(self, options, args):
  39. self.sclient = socket(AF_INET, SOCK_STREAM)
  40. self.sclient.connect((options.ip, int(options.port)))
  41. self.login()
  42. def login(self):
  43. name=input("请输入用户名>>")
  44. password=input("请输入密码>>")
  45. self.json = {"action": "login", "user": name, "password": password}
  46. self.sclient.send(json.dumps(self.json).encode("utf-8"))
  47. data=self.sclient.recv(self.buffersize).decode("utf-8")
  48. # print(data)
  49. if data=="504":
  50. self.name=name
  51. print(dicts[data])
  52. while 1:
  53. code=input("[%s]"%self.name)
  54. cmd_list=code.split()
  55. if hasattr(self,cmd_list[0]):
  56. fun=getattr(self,cmd_list[0])
  57. fun(*cmd_list)
  58. else:
  59. print(dicts[data])
  60. def bufferSize(self):
  61. self.conf_path=os.path.join(self.Base_Dir,"conf","config.ini")
  62. self.conf.read(self.conf_path)
  63. return self.conf.get("client_config", "buffer_size")
  64. def put(self,*cmd_list):
  65. # print("put...")
  66. action,location,target=cmd_list
  67. file_name=os.path.basename(location)
  68. file_size=os.stat(location).st_size
  69. data={"action":action,
  70. "file_name":file_name,
  71. "file_size":file_size,
  72. "target":target}
  73. self.sclient.sendall(json.dumps(data).encode("utf-8"))
  74. data=self.sclient.recv(self.buffersize).decode("utf-8")
  75. self.parseNum(data)
  76. if data=="801":
  77. return
  78. elif data=="802":
  79. choice=input("the file is existing,but not enough,is continue?<Y/N>")
  80. if choice.upper()=="Y":
  81. self.sclient.sendall(choice.upper().encode("utf-8"))
  82. self.size_file =int(self.sclient.recv(self.buffersize).decode("utf-8"))
  83. else:
  84. self.sclient.sendall(choice.upper().encode("utf-8"))
  85. elif data=="803":
  86. pass
  87. f=open(location,"rb")
  88. f.seek(self.size_file)
  89. while self.size_file<file_size:
  90. fdata=f.read(self.buffersize)
  91. self.sclient.sendall(fdata)
  92. self.size_file+=len(fdata)
  93. self.progess(self.size_file, file_size)
  94. def cd(self,*cmd_list):
  95. # print("cd...")
  96. action,position=cmd_list
  97. data={"action":action,
  98. "position":position}
  99. data=json.dumps(data)
  100. self.sclient.sendall(data.encode("utf-8"))
  101. data=self.sclient.recv(self.buffersize).decode("utf-8")
  102. self.name=data
  103. def ls(self,*cmd_list):
  104. action=cmd_list[0]
  105. data={"action":action}
  106. data=json.dumps(data)
  107. self.sclient.sendall(data.encode("utf-8"))
  108. con=self.sclient.recv(self.buffersize).decode("utf-8")
  109. con=list(con)
  110. for i in con:
  111. print(i,end="\r")
  112. def mkdir(self,*cmd_list):
  113. print("mkdir...")
  114. action,position=cmd_list
  115. data={"action":action,
  116. "position":position
  117. }
  118. data=json.dumps(data)
  119. self.sclient.sendall(data.encode("utf-8"))
  120. con=self.sclient.recv(self.buffersize).decode("utf-8")
  121. print(dicts[con])
  122. def parseNum(self,st):
  123. print(dicts[st])
  124. def progess(self,curren,total):
  125. rate=int(curren/total*100)
  126. if rate > 0:
  127. st=sys.stdout
  128. st.write("%s%% %s\r\n"%(rate,"*"*rate))
  129. st.flush()
  130. if rate==100:
  131. print("upload finish!")
  132. #程序入口
  133. if __name__=="__main__":
  134. client_handler()

启动

  1. #服务器启动
  2. python ftp_server start -i 127.0.0.1 -p 8006
  3. #客户端启动
  4. python ftp_client -i 127.0.0.1 -p 8006

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/389748?site
推荐阅读
相关标签
  

闽ICP备14008679号