使用twisted创建管理ftp账号数据库的接口

1.安装twisted和mysql的python驱动

# apt-get install python-twisted
# apt-get install python-mysqldb

 

2、源程序

debian-vm:~# more server.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
###################################
# @author lai
# @date 2010-11-23
##################################
#使用MySQLdb管理ftp数据库接口server端的python实现
#
##################################
import sys
import MySQLdb
import xmlrpclib
from twisted.web import xmlrpc, server, http
from twisted.internet import defer, protocol, reactor
from twisted.python import log
# Set to 0 (debugging off) or 1 (debugging on).
#_DEBUG = 0

##将client的调用记入log
log.startLogging(open('/var/log/xmlrpc.log', 'a'))

Fault = xmlrpclib.Fault

##数据库连接、获取游标
conn = MySQLdb.connect(host='localhost', user='root', passwd='123456',db='ftpusers')
cursor = conn.cursor()

class DBM(xmlrpc.XMLRPC):
        """ A class which works as an XML-RPC server with HTTP basic authentication """
        def __init__(self, user='', password=''):
                self._user = user
                self._password = password
                self._auth = (self._user !='')
                xmlrpc.XMLRPC.__init__(self)
       

##查询单个账号 param=user
        def xmlrpc_getoneuser(self,user):
                conn
                cursor
                sql = 'select * from users where User = %s'
                count = cursor.execute('select * from users where User = %s',user)
                if count != 1: #查询用户是否存在
                        log.msg('Error: xmlrpc call method getoneuser failed: the selected cp acount  %s  is not exist.'%user)
                        return "false"
                else:
                        count = cursor.execute(sql,user)
                        results = cursor.fetchall()
                        log.msg('Info: xmlrpc call method getoneuser sucessfully, the selected cp acount is: %s.'%user)
                        return results

##查询所有账号
        def xmlrpc_getalluser(self):
                conn
                cursor
                sql = 'select * from users'
                count = cursor.execute(sql)
                results = cursor.fetchall()
                log.msg('Info: xmlrpc call method getalluser sucessfully.')
                return results


##创建cp账号 param=(user,newpasswd,dir,status,comment)
        def xmlrpc_adduser(self,user,newpasswd,dir,status,comment):
                conn
                cursor
                sql = 'INSERT INTO `users` (`User`,`Password`,`Dir`,`Status`,`Comment`) VALUES (%s,%s,%s,%s,%s)'
                dir = '/data/ftp/'+dir  #指定用户根目录的绝对路径
        ##字符串合理性检查
                if len(user) < 6: #用户名长度必须大于等于6
                        log.msg('Error: xmlrpc call method adduser failed: the user name lenth of  %s  is too short,and must big tha
n 6.'%user)
                        return "user name length must big 6."
                elif user.startswith('cp') != True: #为便于区分不同ftp用户的类型
                        log.msg('Error: xmlrpc call method adduser failed: the user name  %s  not begin with cp.'%user)
                        return "New add ftpusers must begin with cp"
                else:
                        count = cursor.execute('select * from users where User = %s',user)
                        if count == 1: #检查用户是否存在
                                log.msg('Error: xmlrpc call method adduser failed: the user name  %s  is exist.'%user)
                                return "user: "+user+" already exist!"
                        if newpasswd == '': #确保密码不为空
                                log.msg('Error: xmlrpc call method adduser failed: the newpasswd  %s  is null.'%newpasswd)
                                return "newpasswd must not null."
                        elif status not in ('1','0'): #判断是否锁定用户
                                log.msg('Error: xmlrpc call method adduser failed: the user status  %s  is not 0 or 1.'%status)
                                return "ftpuser Status must be 0 or 1."
                        else:
                                count = cursor.execute(sql,(user,newpasswd,dir,status,comment))
                                log.msg('Info: xmlrpc call method adduser sucessfully: add user   %s  success!.'%user)
                                return "true"

##删除账号 param=user
        def xmlrpc_deluser(self,user):
                conn
                cursor
                sql = 'delete from users where User = %s'
                count = cursor.execute('select * from users where User = %s',user)
                if count != 1: #判断要删除用户是否存在
                        log.msg('Error: xmlrpc call method deluser failed: user  %s  not exist.'%user)
                        return "your remove 用户: "+user+" not exist!"
                else:
                        count = cursor.execute(sql,user)
                        log.msg('Info: xmlrpc call method deluser sucessfully: del user   %s  success!.'%user)
                        return "true"

##修改密码 param=(user,oldpasswd,newpasswd)
        def xmlrpc_changepasswd(self,user,oldpasswd,newpasswd):
                conn
                cursor
                sql = 'UPDATE users SET Password = %s WHERE User = %s'
                count = cursor.execute('select * from users where User = %s',user)
                results = cursor.fetchall()
                if count != 1:  #检查用户是否存在
                        log.msg('Error: xmlrpc call method changepasswd failed: user  %s  not exist.'%user)
                        return "your modpasswd's 用户: "+user+" not exist!"
                elif results[0][1] != oldpasswd: #检查旧密码输入是否正确
                        log.msg('Error: xmlrpc call method changepasswd failed: oldpasswd  %s  wrong.'%oldpasswd)
                        return "old passwd is incrrect,please input agin."
                elif len(newpasswd) == 0: #检查新密码是否为空
                        log.msg('Error: xmlrpc call method changepasswd failed: newpasswd  %s  is null.'%newpasswd)
                        return "new passwd must not null"
                elif oldpasswd == newpasswd: #检查新旧密码是否相同
                        log.msg('Error: xmlrpc call method changepasswd failed: newpasswd  and oldpaaswd same.')
                        return "change passwd faild: the old passwd and new passwd must not be the same"
                else:
                        count = cursor.execute(sql,(newpasswd,user))
                        log.msg('Info: xmlrpc call method changepasswd sucessfully: user %s passwd changed successully.'%user)
                        return "true"

##重置密码 param=(user,newpasswd)
        def xmlrpc_resetpasswd(self,user,newpasswd):
                conn
                cursor
                sql = 'UPDATE users SET Password = %s WHERE User = %s'
                count = cursor.execute('select * from users where User = %s',user)
                results = cursor.fetchall()
                if count != 1:  #检查用户是否存在
                        log.msg('Error: xmlrpc call method resetpasswd failed: user  %s  not exist.'%user)
                        return "your modpasswd's 用户: "+user+" not exist!"
                elif len(newpasswd) == 0: #检查新密码是否为空
                        log.msg('Error: xmlrpc call method resetpasswd failed: newpasswd  %s  is null.'%newpasswd)
                        return "new passwd must not null"
                else:
                        count = cursor.execute(sql,(newpasswd,user))
                        log.msg('Info: xmlrpc call method resetpasswd sucessfully: user %s passwd changed successully.'%user)
                        return "true"

##设置配额 param=(user,quotesize)
        def xmlrpc_setquotasize(self,user,quotesize):
                conn
                cursor
                sql = 'UPDATE users SET  QuotaSize = %s WHERE User = %s'
                count = cursor.execute('select * from users where User = %s',user)
                if count != 1:  #检查用户是否存在
                        log.msg('Error: xmlrpc call method setquotasize failed: user  %s  not exist.'%user)
                        return "your set qutosize's 用户: "+user+" not exist!"
                else:
                        count = cursor.execute(sql,(quotesize,user))
                        log.msg('Error: xmlrpc call method setquotasize sucessfully: user  %s  QuotaSize set to %s MB successully.'%
(user,quotesize))
                        return "true"


        def render(self, request):
                """ Overridden 'render' method which takes care of
                HTTP basic authorization """
                if self._auth:
                        cleartext_token = self._user + ':' + self._password
                        user = request.getUser()
                        passwd = request.getPassword()
                        if user=='' and passwd=='':
                                request.setResponseCode(http.UNAUTHORIZED)
                                return 'Authorization required!'
                        else:
                                token = user + ':' + passwd
                                if token != cleartext_token:
                                        request.setResponseCode(http.UNAUTHORIZED)
                                        return 'Authorization Failed!'
                request.content.seek(0, 0)
                args, functionPath = xmlrpclib.loads(request.content.read())
                try:
                        function = self._getFunction(functionPath)
                except Fault, f:
                        self._cbRender(f, request)
                else:
                        request.setHeader("content-type", "text/xml")
                        defer.maybeDeferred(function, *args).addErrback(
                        self._ebRender
                        ).addCallback(
                        self._cbRender, request
                        )
                return server.NOT_DONE_YET

s = DBM('user2','pass2')
reactor.listenTCP(8080, server.Site(s))

print "Listening on port 8080"
reactor.run()

 

3、后台运行该接口

#  more runserver
#!/bin/bash
nohup python server.py &

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值