python3实现ftp服务功能(客户端)


Posted in Python onMarch 24, 2017

本文实例为大家分享了python3实现ftp服务功能的具体代码,供大家参考,具体内容如下

客户端 main代码:

#Author by Andy
#_*_ coding:utf-8 _*_
'''
This program is used to create a ftp client

'''
import socket,os,json,time,hashlib,sys
class Ftp_client(object):
 def __init__(self):
  self.client = socket.socket()
 def help(self):
  msg = '''useage:
  ls
  pwd
  cd dir(example: / .. . /var)
  put filename
  rm filename
  get filename
  mkdir directory name
  '''
  print(msg)
 def connect(self,addr,port):
  self.client.connect((addr,port))
 def auth(self):
  m = hashlib.md5()
  username = input("请输入用户名:").strip()

  m.update(input("请输入密码:").strip().encode())
  password = m.hexdigest()
  user_info = {
   'action':'auth',
   'username':username,
   'password':password}
  self.client.send(json.dumps(user_info).encode('utf-8'))
  server_response = self.client.recv(1024).decode()
  # print(server_response)
  return server_response
 def interactive(self):
  while True:
   msg = input(">>>:").strip()
   if not msg:
    print("不能发送空内容!")
    continue
   cmd = msg.split()[0]
   if hasattr(self,cmd):
    func = getattr(self,cmd)
    func(msg)
   else:
    self.help()
    continue
 def put(self,*args):
  cmd_split = args[0].split()
  if len(cmd_split) > 1:
   filename = cmd_split[1]
   if os.path.isfile(filename):
    filesize = os.stat(filename).st_size
    file_info = {
     "action":"put",
     "filename":filename,
     "size":filesize,
     "overriding":'True'
    }
    self.client.send( json.dumps(file_info).encode('utf-8') )
    #防止粘包,等待服务器确认。
    request_code = {
     '200': 'Ready to recceive data!',
     '210': 'Not ready to received data!'
    }
    server_response = self.client.recv(1024).decode()
    if server_response == '200':
     f = open(filename,"rb")
     send_size = 0
     start_time = time.time()
     for line in f:
      self.client.send(line)
      send_size += len(line)
      send_percentage = int((send_size / filesize) * 100)
      while True:
       progress = ('\r已上传%sMB(%s%%)' % (round(send_size / 102400, 2), send_percentage)).encode(
        'utf-8')
       os.write(1, progress)
       sys.stdout.flush()
       time.sleep(0.0001)
       break
     else:
      end_time = time.time()
      time_use = int(end_time - start_time)
      print("\nFile %s has been sent successfully!" % filename)
      print('\n平均下载速度%s MB/s' % (round(round(send_size / 102400, 2) / time_use, 2)))
      f.close()
    else:
     print("Sever isn't ready to receive data!")
     time.sleep(10)
     start_time = time.time()
     f = open(filename, "rb")
     send_size = 0
     for line in f:
       self.client.send(line)
       send_size += len(line)
       # print(send_size)
       while True:
        send_percentage = int((send_size / filesize) * 100)
        progress = ('\r已上传%sMB(%s%%)' % (round(send_size / 102400, 2), send_percentage)).encode(
         'utf-8')
        os.write(1, progress)
        sys.stdout.flush()
        # time.sleep(0.0001)
        break
     else:
      end_time = time.time()
      time_use = int(end_time - start_time)
      print("File %s has been sent successfully!" % filename)
      print('\n平均下载速度%s MB/s' % (round(round(send_size / 102400, 2) / time_use, 2)))
      f.close()
   else:
    print("File %s is not exit!" %filename)
  else:
   self.help()
 def ls(self,*args):
  cmd_split = args[0].split()
  # print(cmd_split)
  if len(cmd_split) > 1:
   path = cmd_split[1]
  elif len(cmd_split) == 1:
   path = '.'
  request_info = {
   'action': 'ls',
   'path': path
  }
  self.client.send(json.dumps(request_info).encode('utf-8'))
  sever_response = self.client.recv(1024).decode()
  print(sever_response)
 def pwd(self,*args):
  cmd_split = args[0].split()
  if len(cmd_split) == 1:
   request_info = {
    'action': 'pwd',
   }
   self.client.send(json.dumps(request_info).encode("utf-8"))
   server_response = self.client.recv(1024).decode()
   print(server_response)
  else:
   self.help()
 def get(self,*args):
  cmd_split = args[0].split()
  if len(cmd_split) > 1:
   filename = cmd_split[1]
   file_info = {
     "action": "get",
     "filename": filename,
     "overriding": 'True'
    }
   self.client.send(json.dumps(file_info).encode('utf-8'))
   server_response = self.client.recv(1024).decode() #服务器反馈文件是否存在
   self.client.send('0'.encode('utf-8'))
   if server_response == '0':
    file_size = int(self.client.recv(1024).decode())
    # print(file_size)
    self.client.send('0'.encode('utf-8')) #确认开始传输数据
    if os.path.isfile(filename):
     filename = filename+'.new'
    f = open(filename,'wb')
    receive_size = 0
    m = hashlib.md5()
    start_time = time.time()
    while receive_size < file_size:
     if file_size - receive_size > 1024: # 还需接收不止1次
      size = 1024
     else:
      size = file_size - receive_size
     data = self.client.recv(size)
     m.update(data)
     receive_size += len(data)
     data_percent=int((receive_size / file_size) * 100)
     f.write(data)
     progress = ('\r已下载%sMB(%s%%)' %(round(receive_size/102400,2),data_percent)).encode('utf-8')
     os.write(1,progress)
     sys.stdout.flush()
     time.sleep(0.0001)

    else:
     end_time = time.time()
     time_use = int(end_time - start_time)
     print('\n平均下载速度%s MB/s'%(round(round(receive_size/102400,2)/time_use,2)))
     Md5_server = self.client.recv(1024).decode()
     Md5_client = m.hexdigest()
     print('文件校验中,请稍候...')
     time.sleep(0.3)
     if Md5_server == Md5_client:
      print('文件正常。')
     else:
      print('文件与服务器MD5值不符,请确认!')
   else:
    print('File not found!')
    client.interactive()
  else:
   self.help()
 def rm(self,*args):
  cmd_split = args[0].split()
  if len(cmd_split) > 1:
   filename = cmd_split[1]
   request_info = {
    'action':'rm',
    'filename': filename,
    'prompt':'Y'
   }
   self.client.send(json.dumps(request_info).encode("utf-8"))
   server_response = self.client.recv(10240).decode()
   request_code = {
    '0':'confirm to deleted',
    '1':'cancel to deleted'
   }

   if server_response == '0':
    confirm = input("请确认是否真的删除该文件:")
    if confirm == 'Y' or confirm == 'y':
     self.client.send('0'.encode("utf-8"))
     print(self.client.recv(1024).decode())
    else:
     self.client.send('1'.encode("utf-8"))
     print(self.client.recv(1024).decode())
   else:
    print('File not found!')
    client.interactive()


  else:
   self.help()
 def cd(self,*args):
  cmd_split = args[0].split()
  if len(cmd_split) > 1:
   path = cmd_split[1]
  elif len(cmd_split) == 1:
   path = '.'
  request_info = {
   'action':'cd',
   'path':path
  }
  self.client.send(json.dumps(request_info).encode("utf-8"))
  server_response = self.client.recv(10240).decode()
  print(server_response)
 def mkdir(self,*args):
  request_code = {
   '0': 'Directory has been made!',
   '1': 'Directory is aleady exist!'
  }
  cmd_split = args[0].split()
  if len(cmd_split) > 1:
   dir_name = cmd_split[1]
   request_info = {
    'action':'mkdir',
    'dir_name': dir_name
   }
   self.client.send(json.dumps(request_info).encode("utf-8"))
   server_response = self.client.recv(1024).decode()
   if server_response == '0':
    print('Directory has been made!')
   else:
    print('Directory is aleady exist!')
  else:
   self.help()
 # def touch(self,*args):
def run():
 client = Ftp_client()
 # client.connect('10.1.2.3',6969)
 Addr = input("请输入服务器IP:").strip()
 Port = int(input("请输入端口号:").strip())
 client.connect(Addr,Port)
 while True:
  if client.auth() == '0':
   print("Welcome.....")
   client.interactive()
   break
  else:
   print("用户名或密码错误!")
   continue

目录结构:

python3实现ftp服务功能(客户端)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python函数中定义参数的四种方式
Nov 30 Python
Python中的__SLOTS__属性使用示例
Feb 18 Python
Python模块结构与布局操作方法实例分析
Jul 24 Python
Python基于回溯法子集树模板实现8皇后问题
Sep 01 Python
PYTHON基础-时间日期处理小结
May 05 Python
Django 忘记管理员或忘记管理员密码 重设登录密码的方法
May 30 Python
Python List cmp()知识点总结
Feb 18 Python
详解Python中is和==的区别
Mar 21 Python
Python简易版停车管理系统
Aug 12 Python
协程Python 中实现多任务耗资源最小的方式
Oct 19 Python
scrapy头部修改的方法详解
Dec 06 Python
5个pandas调用函数的方法让数据处理更加灵活自如
Apr 24 Python
Python 中urls.py:URL dispatcher(路由配置文件)详解
Mar 24 #Python
python 类详解及简单实例
Mar 24 #Python
Python类的动态修改的实例方法
Mar 24 #Python
Python操作Excel之xlsx文件
Mar 24 #Python
解决uWSGI的编码问题详解
Mar 24 #Python
Python中动态创建类实例的方法
Mar 24 #Python
python3中set(集合)的语法总结分享
Mar 24 #Python
You might like
一个odbc连mssql分页的类
2006/10/09 PHP
PHP新手上路(三)
2006/10/09 PHP
PHP DataGrid 实现代码
2009/08/12 PHP
PHP连接SQLServer2005的实现方法(附ntwdblib.dll下载)
2012/07/02 PHP
浅析application/x-www-form-urlencoded和multipart/form-data的区别
2014/06/22 PHP
php实现插入数组但不影响原有顺序的方法
2015/03/27 PHP
PHP+Mysql+jQuery文件下载次数统计实例讲解
2015/10/10 PHP
laravel接管Dingo-api和默认的错误处理方式
2019/10/25 PHP
jquery插件jTimer(jquery定时器)使用方法
2013/12/23 Javascript
《JavaScript函数式编程》读后感
2015/08/07 Javascript
Document.body.scrollTop的值总为零的快速解决办法
2016/06/09 Javascript
window.open不被拦截的简单实现代码(推荐)
2016/08/04 Javascript
JS简单实现数组去重的方法示例
2017/03/27 Javascript
bootstrap table表格客户端分页实例
2017/08/07 Javascript
Vue2.X 通过AJAX动态更新数据
2018/07/17 Javascript
JavaScript fetch接口案例解析
2018/08/30 Javascript
Vue起步(无cli)的啊教程详解
2019/04/11 Javascript
Node.js path模块,获取文件后缀名操作
2020/11/07 Javascript
[02:35]DOTA2超级联赛专访XB 难忘一年九冠称王
2013/06/20 DOTA
Pycharm设置界面全黑的方法
2018/05/23 Python
Python使用numpy模块创建数组操作示例
2018/06/20 Python
解决python "No module named pip" 的问题
2018/10/13 Python
Python Pillow Image Invert
2019/01/22 Python
python画图的函数用法以及技巧
2019/06/28 Python
Flask框架中request、请求钩子、上下文用法分析
2019/07/23 Python
python自动循环定时开关机(非重启)测试
2019/08/26 Python
python或C++读取指定文件夹下的所有图片
2019/08/31 Python
Python实现TCP探测目标服务路由轨迹的原理与方法详解
2019/09/04 Python
python 实现图片上传接口开发 并生成可以访问的图片url
2019/12/18 Python
日本最大化妆品和美容产品的综合口碑网站:cosme shopping
2019/08/28 全球购物
澳洲Chemist Direct药房中文网:澳洲大型线上直邮药房
2019/11/04 全球购物
酒店管理毕业生自荐信
2013/10/24 职场文书
淘宝中秋节活动方案
2014/01/31 职场文书
农业项目建议书
2014/08/25 职场文书
处级领导干部四风问题自我剖析材料
2014/09/29 职场文书
PostgreSQL将数据加载到buffer cache中操作方法
2021/04/16 PostgreSQL