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 相关文章推荐
Django1.3添加app提示模块不存在的解决方法
Aug 26 Python
Python基于动态规划算法解决01背包问题实例
Dec 06 Python
Python实现从log日志中提取ip的方法【正则提取】
Mar 31 Python
Python将图片转换为字符画的方法
Jun 16 Python
在Python 不同级目录之间模块的调用方法
Jan 19 Python
python打开windows应用程序的实例
Jun 28 Python
python之生产者消费者模型实现详解
Jul 27 Python
pytorch .detach() .detach_() 和 .data用于切断反向传播的实现
Dec 27 Python
opencv python在视屏上截图功能的实现
Mar 05 Python
Python多线程操作之互斥锁、递归锁、信号量、事件实例详解
Mar 24 Python
如何使用PyCharm将代码上传到GitHub上(图文详解)
Apr 27 Python
Python中logger日志模块详解
Aug 04 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
社区(php&amp;&amp;mysql)六
2006/10/09 PHP
PHP+Mysql树型结构(无限分类)数据库设计的2种方式实例
2014/07/15 PHP
PHP常用的排序和查找算法
2015/08/06 PHP
PHP登录验证码的实现与使用方法
2016/07/07 PHP
Laravel 修改默认日志文件名称和位置的例子
2019/10/17 PHP
laravel与thinkphp之间的区别与优缺点
2021/03/02 PHP
打开超链需要“确认”对话框的方法
2007/03/08 Javascript
jquery.jstree 增加节点的双击事件代码
2010/07/27 Javascript
jQuery使用andSelf()来包含之前的选择集
2014/05/19 Javascript
jQuery中live()方法用法实例
2015/01/19 Javascript
JS操作HTML自定义属性的方法
2015/02/10 Javascript
Javascript中Array用法实例分析
2015/06/13 Javascript
jquery中val()方法是从最后一个选项往前读取的
2015/09/06 Javascript
JS密码生成与强度检测完整实例(附demo源码下载)
2016/04/06 Javascript
浅谈js控制li标签排序问题 js调用php函数的方法
2016/10/16 Javascript
Angular4绑定html内容出现警告的处理方法
2017/11/03 Javascript
微信小程序实现多选删除列表数据功能示例
2019/01/15 Javascript
[01:49]一目了然!DOTA2DotA快捷操作对比第二弹
2014/05/16 DOTA
[01:12:53]完美世界DOTA2联赛PWL S2 Forest vs SZ 第一场 11.25
2020/11/26 DOTA
[01:08:43]DOTA2-DPC中国联赛定级赛 Phoenix vs DLG BO3第一场 1月9日
2021/03/11 DOTA
Python实现对PPT文件进行截图操作的方法
2015/04/28 Python
python实现决策树分类(2)
2018/08/30 Python
Python批量生成幻影坦克图片实例代码
2019/06/04 Python
python爬虫 爬取58同城上所有城市的租房信息详解
2019/07/30 Python
Python 合并多个TXT文件并统计词频的实现
2019/08/23 Python
Pytorch损失函数nn.NLLLoss2d()用法说明
2020/07/07 Python
详解numpy.ndarray.reshape()函数的参数问题
2020/10/13 Python
马来西亚在线购物:POPLOOK.com
2019/12/09 全球购物
高三高考决心书
2014/03/11 职场文书
2014年五四青年节演讲比赛方案
2014/04/22 职场文书
幼儿园课题实施方案
2014/05/14 职场文书
社区三八妇女节活动总结
2015/02/06 职场文书
2016继续教育研修日志
2015/11/13 职场文书
HR必备:销售经理聘用合同范本
2019/08/21 职场文书
实习员工转正的评语汇总,以备不时之需
2019/12/17 职场文书
MySQL 数据类型选择原则
2021/05/27 MySQL