python3实现ftp服务功能(服务端 For Linux)


Posted in Python onMarch 24, 2017

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

功能介绍:

可执行的命令:

ls
pwd
cd
put
rm
get
mkdir

1、用户加密认证

2、允许多用户同时登陆

3、每个用户有自己的家目录,且只可以访问自己的家目录

4、运行在自己家目录下随意切换目录

5、允许上传下载文件,且文件一致

6、传输过程中显示进度条
server main 代码:

# Author by Andy
# _*_ coding:utf-8 _*_
import os, sys, json, hashlib, socketserver, time

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from conf import userdb_set
class Ftp_server(socketserver.BaseRequestHandler):
 user_home_dir = ''
 def auth(self, *args):
  '''验证用户名及密码'''
  cmd_dic = args[0]
  username = cmd_dic["username"]
  password = cmd_dic["password"]
  f = open(userdb_set.userdb_set(), 'r')
  user_info = json.load(f)
  if username in user_info.keys():
   if password == user_info[username]:
    self.request.send('0'.encode())
    os.chdir('/home/%s' % username)
    self.user_home_dir = os.popen('pwd').read().strip()
    data = "%s login successed" % username
    self.loging(data)
   else:
    self.request.send('1'.encode())
    data = "%s login failed" % username
    self.loging(data)
    f.close
  else:
   self.request.send('1'.encode())
   data = "%s login failed" % username
   self.loging(data)
   f.close
   ##########################################

 def get(self, *args):
  '''给客户端传输文件'''
  request_code = {
   '0': 'file is ready to get',
   '1': 'file not found!'
  }
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  filename = cmd_dic["filename"]
  if os.path.isfile(filename):
   self.request.send('0'.encode('utf-8')) # 确认文件存在
   self.request.recv(1024)
   self.request.send(str(os.stat(filename).st_size).encode('utf-8'))
   self.request.recv(1024)
   m = hashlib.md5()
   f = open(filename, 'rb')
   for line in f:
    m.update(line)
    self.request.send(line)
   self.request.send(m.hexdigest().encode('utf-8'))
   print('From server:Md5 value has been sended!')
   f.close()
  else:
   self.request.send('1'.encode('utf-8'))
   ###########################################

 def cd(self, *args):
  '''执行cd命令'''
  user_current_dir = os.popen('pwd').read().strip()
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  path = cmd_dic['path']
  if path.startswith('/'):
   if self.user_home_dir in path:
    os.chdir(path)
    new_dir = os.popen('pwd').read()
    user_current_dir = new_dir
    self.request.send('Change dir successfully!'.encode("utf-8"))
    data = 'Change dir successfully!'
    self.loging(data)
   elif os.path.exists(path):
    self.request.send('Permission Denied!'.encode("utf-8"))
    data = 'Permission Denied!'
    self.loging(data)
   else:
    self.request.send('Directory not found!'.encode("utf-8"))
    data = 'Directory not found!'
    self.loging(data)
  elif os.path.exists(path):
   os.chdir(path)
   new_dir = os.popen('pwd').read().strip()
   if self.user_home_dir in new_dir:
    self.request.send('Change dir successfully!'.encode("utf-8"))
    user_current_dir = new_dir
    data = 'Change dir successfully!'
    self.loging(data)
   else:
    os.chdir(user_current_dir)
    self.request.send('Permission Denied!'.encode("utf-8"))
    data = 'Permission Denied!'
    self.loging(data)
  else:
   self.request.send('Directory not found!'.encode("utf-8"))
   data = 'Directory not found!'
   self.loging(data)
   ###########################################

 def rm(self, *args):
  request_code = {
   '0': 'file exist,and Please confirm whether to rm',
   '1': 'file not found!'
  }
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  filename = cmd_dic['filename']
  if os.path.exists(filename):
   self.request.send('0'.encode("utf-8")) # 确认文件存在
   client_response = self.request.recv(1024).decode()
   if client_response == '0':
    os.popen('rm -rf %s' % filename)
    self.request.send(('File %s has been deleted!' % filename).encode("utf-8"))
    self.loging('File %s has been deleted!' % filename)
   else:
    self.request.send(('File %s not deleted!' % filename).encode("utf-8"))
    self.loging('File %s not deleted!' % filename)
  else:
   self.request.send('1'.encode("utf-8"))
   ########################################

 def pwd(self, *args):
  '''执行pwd命令'''
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  server_response = os.popen('pwd').read().strip().encode("utf-8")
  self.request.send(server_response)

 #############################################
 def ls(self, *args):
  '''执行ls命名'''
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  path = cmd_dic['path']
  cmd = 'ls -l %s' % path
  server_response = os.popen(cmd).read().encode("utf-8")
  self.request.send(server_response)

 ############################################
 def put(self, *args):
  '''接收客户端文件'''
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  filename = cmd_dic["filename"]
  filesize = cmd_dic["size"]
  if os.path.isfile(filename):
   f = open(filename + '.new', 'wb')
  else:
   f = open(filename, 'wb')
  request_code = {
   '200': 'Ready to recceive data!',
   '210': 'Not ready to received data!'
  }
  self.request.send('200'.encode())
  receive_size = 0
  while True:
   if receive_size < filesize:
    data = self.request.recv(1024)
    f.write(data)
    receive_size += len(data)
   else:
    data = "File %s has been uploaded successfully!" % filename
    self.loging(data)
    print(data)
    break

    ################################################

 def mkdir(self, *args):
  request_code = {
   '0': 'Directory has been made!',
   '1': 'Directory is aleady exist!'
  }
  cmd_dic = args[0]
  self.loging(json.dumps(cmd_dic))
  dir_name = cmd_dic['dir_name']
  if os.path.exists(dir_name):
   self.request.send('1'.encode("utf-8"))
  else:
   os.popen('mkdir %s' % dir_name)
   self.request.send('0'.encode("utf-8"))

   #############################################

  def loging(self, data):
  '''日志记录'''
  localtime = time.asctime(time.localtime(time.time()))
  log_file = '/root/ftp/ftpserver/log/server.log'
  with open(log_file, 'a', encoding='utf-8') as f:
   f.write('%s-->' % localtime + data + '\n')
   ##############################################

 def handle(self):
  # print("您本次访问使用的IP为:%s" %self.client_address[0])
  # localtime = time.asctime( time.localtime(time.time()))
  # print(localtime)

  while True:
   try:
    self.data = self.request.recv(1024).decode() #
    # print(self.data)
    cmd_dic = json.loads(self.data)
    action = cmd_dic["action"]
    # print("用户请求%s"%action)
    if hasattr(self, action):
     func = getattr(self, action)
     func(cmd_dic)
   except Exception as e:
    self.loging(str(e))
    break

def run():
 HOST, PORT = '0.0.0.0', 6969
 print("The server is started,and listenning at port 6969")
 server = socketserver.ThreadingTCPServer((HOST, PORT), Ftp_server)
 server.serve_forever()
if __name__ == '__main__':
 run()

设置用户口令代码:

#Author by Andy
#_*_ coding:utf-8 _*_
import os,json,hashlib,sys

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
userdb_file = base_dir+"\data\\userdb"
# print(userdb_file)
def userdb_set():
 if os.path.isfile(userdb_file):
  # print(userdb_file)
  return userdb_file
 else:
  print('请先为您的服务器创建用户!')
  user_data = {}
  dict={}
  Exit_flags = True
  while Exit_flags:
   username = input("Please input username:")
   if username != 'exit':
    password = input("Please input passwod:")
    if password != 'exit':
      user_data.update({username:password})
      m = hashlib.md5()
      # m.update('hello')
      # print(m.hexdigest())
      for i in user_data:
       # print(i,user_data[i])
       m.update(user_data[i].encode())
       dict.update({i:m.hexdigest()})
    else:
     break
   else:
    break
  f = open(userdb_file,'w')
  json.dump(dict,f)
  f.close()
 return userdb_file

目录结构:

python3实现ftp服务功能(服务端 For Linux)

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

Python 相关文章推荐
一些常用的Python爬虫技巧汇总
Sep 28 Python
Python3中的列表,元组,字典,字符串相关知识小结
Nov 10 Python
Python+PIL实现支付宝AR红包
Feb 09 Python
python实现最长公共子序列
May 22 Python
python 编写简单网页服务器的实例
Jun 01 Python
python 批量解压压缩文件的实例代码
Jun 27 Python
python修改FTP服务器上的文件名
Sep 11 Python
YUV转为jpg图像的实现
Dec 09 Python
Python time库基本使用方法分析
Dec 13 Python
python 类之间的参数传递方式
Dec 20 Python
python中字典增加和删除使用方法
Sep 30 Python
使用python如何删除同一文件夹下相似的图片
May 07 Python
python3实现ftp服务功能(客户端)
Mar 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
You might like
漫威DC御用漫画家去世 他的表情包曾走红网络
2020/04/09 欧美动漫
将酷狗krc歌词解析并转换为lrc歌词php源码
2014/06/20 PHP
PHP命名空间和自动加载类
2016/04/03 PHP
PHP设计模式之原型设计模式原理与用法分析
2018/04/25 PHP
使用prototype.js进行异步操作
2007/02/07 Javascript
表单提交时自动复制内容到剪贴板的js代码
2007/03/16 Javascript
JavaScript 实现模态对话框 源代码大全
2009/05/02 Javascript
Jquery结合HTML5实现文件上传
2015/06/25 Javascript
基于jQuery插件实现点击小图显示大图效果
2016/05/11 Javascript
Javascript基础知识盲点总结之函数
2016/05/15 Javascript
javascript类型系统_正则表达式RegExp类型详解
2016/06/24 Javascript
jQuery实现两个select控件的互移操作
2016/12/22 Javascript
jQuery ajax实现省市县三级联动
2021/03/07 Javascript
AngularJS 异步解决实现方法
2017/06/12 Javascript
vue实现点击关注后及时更新列表功能
2018/06/26 Javascript
Electron中实现大文件上传和断点续传功能
2018/10/28 Javascript
微信小程序实现卡片层叠滑动效果
2019/06/21 Javascript
elementUi vue el-radio 监听选中变化的实例代码
2019/06/28 Javascript
微信小程序中如何计算距离某个节日还有多少天
2019/07/15 Javascript
[19:54]夜魇凡尔赛茶话会 第一期02:看图识人
2021/03/11 DOTA
flask框架实现连接sqlite3数据库的方法分析
2018/07/16 Python
django框架用户权限中的session缓存到redis中的方法
2019/08/06 Python
Python 类的魔法属性用法实例分析
2019/11/21 Python
python字符串的index和find的区别详解
2020/06/20 Python
利用纯css3实现的文字亮光特效的代码演示
2014/11/27 HTML / CSS
Myprotein加拿大官网:欧洲第一的运动营养品牌
2018/01/06 全球购物
Under Armour安德玛荷兰官网:美国高端运动科技品牌
2019/07/10 全球购物
类、抽象类、接口的差异
2016/06/13 面试题
opencv实现图像几何变换
2021/03/24 Python
六十岁生日答谢词
2014/01/10 职场文书
关于毕业的中学校园广播稿
2014/01/26 职场文书
主管竞聘书范文
2014/03/31 职场文书
优秀应届毕业生自荐书
2014/06/29 职场文书
运动员入场词
2015/07/18 职场文书
关于实现中国梦的心得体会
2016/01/05 职场文书
Python加密与解密模块hashlib与hmac
2022/06/05 Python