Python创建、删除、查询vsftpd的虚拟用户(虚拟用户使用MySQL数据库)

原创 2016年05月30日 18:52:01

写在前面:
1. 初学python,使用python对vsftpd的虚拟用户进行增、删、查操作。
2. 小弟的英语比较菜,请忽略英语语法错误。^_^
3. 该程序主要练习MySQLdb、getpass模块的使用。需要安装MySQL-python软件包。

VSFTPD的使用,请参阅:http://blog.csdn.net/xrwwuming/article/details/51505857

代码


#!/usr/bin/env pyton
# -*- coding: utf-8 -*-


import MySQLdb
import getpass
import sys

mysqlHost = 'localhost'
mysqlUser = 'vsftp'
mysqlPass = 'ftpvuser'
mysqlDB = 'vsftp'
mysqlTable = 'vuser'

def connectDb():
    global conn
    global cursor
    try:
        conn = MySQLdb.connect(host=mysqlHost, user=mysqlUser, passwd=mysqlPass, db=mysqlDB)
        cursor = conn.cursor()
        connectResult = True
    except:
        print 'Error: Can not connect to mysql database, please check it, Quit.'
        connectResult = False

    return connectResult


def checkUser(comm):
    cursor.execute(comm)
    rows = cursor.rowcount

    if rows != 0:
        result = True
    else:
        result = False

    return result

def closes():
    cursor.close()
    conn.close()

def tips():
    raw_input('Enter any key to continue? ')

def userList():
    comm = "select * from %s;" % mysqlTable
    cursor.execute(comm)
    rows = cursor.fetchall()
    print 'Current Users'.center(40,'=')

    for row in rows:
        print 'Username: %s' % (row[0])

    print
    print 'Total User: %d' % (cursor.rowcount)
    print 'END'.center(40,'=')


def add():
    addUserResult = False
    if connectDb():   
        while not addUserResult:
            try:
                username = raw_input('Enter Username: ').strip()  
                checkUserComm = "select * from %s where username = '%s';" % (mysqlTable, username)  
                result = checkUser(checkUserComm)       

                if len(username) == 0: 
                    print 'username can not empty , please try again...'
                elif result:  
                    print 'username %s is exist, please use other account, try again...' % (username)
                else:
                    while not addUserResult:  
                        password = getpass.getpass('Enter Password: ') 
                        confirmPassword = getpass.getpass('Confirm Password: ')  
                        if len(password) == 0 or len(confirmPassword) == 0:   
                            print 'password or confirm password can not empty, please try again...'
                        elif password != confirmPassword:  
                            print 'password is mismatch, please try again...'
                        else:
                            addUser = "insert into %s values ('%s',password('%s'));" % (mysqlTable, username, password) 
                            cursor.execute(addUser)  
                            conn.commit()             
                            if checkUser(checkUserComm): 
                                print            
                                print 'Add result'.center(40,'=')
                                print 'Add user %s successful' % (username)
                                print 'END'.center(40,'=')
                                closes()
                                addUserResult = True
                                tips()
                            else:
                                print
                                print 'Add result'.center(40,'=')
                                print 'Add user %s failed, please try again...'
                                print 'END'.center(40,'=')
                                closes()
                                addUserResult = True
                                tips()
            except (KeyboardInterrupt, EOFError, SystemExit):
                print 'Quit Program'
                sys.exit()
    else:
        sys.exit()


def delete():
    deleteUserResult = False
    if connectDb():
        userList()
        while not deleteUserResult:
            try:
                username = raw_input('Enter username you want to delete: ').strip() 
                checkUserComm = "select * from %s where username = '%s';" % (mysqlTable, username)   
                result = checkUser(checkUserComm)  
                if len(username) == 0:
                    print 'username can not empty, please try again...'
                elif not result:
                    print 'username %s is not exist, please try again...'  % (username)
                else:
                    deleteUser = "delete from %s where username = '%s'" % (mysqlTable, username)
                    cursor.execute(deleteUser)   
                    conn.commit()             
                    if not checkUser(checkUserComm):     
                        print        
                        print 'Delete result'.center(40,'=')
                        print 'Delete user %s successful' % (username)
                        print 'END'.center(40,'=')
                        closes()
                        deleteUserResult = True
                        tips()
                    else:
                        print
                        print 'Delete result'.center(40,'=')
                        print 'Delete user %s failed, please try again...'
                        print 'END'.center(40,'=')
                        closes()
                        deleteUserResult = True
                        tips()
            except (KeyboardInterrupt, EOFError, SystemExit):
                print 'Quit Program'
                sys.exit()
    else:
        sys.exit()


def show():
    comm = "select * from %s;" % mysqlTable
    if connectDb():
        userList()
        closes()
        tips()

def showMenu():
    select = 'adsq'

    menu='''
=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? ''' 


    while True:
        try:
            choice = raw_input(menu).strip().lower()[0]
        except (KeyboardInterrupt, SystemExit, EOFError, IndexError):
            choice = 'q'

        if choice not in select:
            print
            print "Invalid Choice , please try again..."
            continue

        if choice == 'q':
            break

        return choice

if __name__ == '__main__':
    while True:
        choice = showMenu()

        if choice == 'a':
            add()
        elif choice == 'd':
            delete()
        elif choice == 's':
            show()
        else:
            print "Quit Program"
            break

[root@control ~]# 

测试

说明:
1. 添加用户时,程序会检测用户名是否为空,且不能是已经存在的用户。
2. 用户输入的密码不能为空,并且两次输入的密码必须要一致。
3. 密码使用password函数加密,存储在mysql数据库中。
4. 删除用户时,系统会将当前数据库中的用户显示出来,并且删除的用户不能为空,且必须是已经存在的。

添加用户

[root@control ~]# python vsftp_mysql_user_config.py 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? s
=============Current Users==============
Username: ftp01
Username: ftp02

Total User: 2
==================END===================
Enter any key to continue? 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? a
Enter Username: ftp01
username ftp01 is exist, please use other account, try again...
Enter Username: ftp03
Enter Password: 
Confirm Password: 
password is mismatch, please try again...
Enter Password: 
Confirm Password: 

===============Add result===============
Add user ftp03 successful
==================END===================
Enter any key to continue? 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? s
=============Current Users==============
Username: ftp01
Username: ftp02
Username: ftp03

Total User: 3
==================END===================
Enter any key to continue? 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? q
Quit Program
[root@control ~]# 

删除用户

[root@control ~]# python vsftp_mysql_user_config.py 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? d
=============Current Users==============
Username: ftp01
Username: ftp02
Username: ftp03

Total User: 3
==================END===================
Enter username you want to delete: ftp04
username ftp04 is not exist, please try again...
Enter username you want to delete: ftp03

=============Delete result==============
Delete user ftp03 successful
==================END===================
Enter any key to continue? 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? s
=============Current Users==============
Username: ftp01
Username: ftp02

Total User: 2
==================END===================
Enter any key to continue? 

=========== Menu ============
    A)dd user
    D)elete user
    S)how all users
    Q)uit
=============================
Enter your choice: [A/D/S/Q]? q
Quit Program
[root@control ~]# 
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Debian系统下利用vsdftpd+Mysql实现虚拟用户登录(Debian+vsftpd+Mysql)

vsftpd是Linux系统中继Wu-ftpd之后又是款优秀的、普遍使用的FTp服务器。vsftpd是very secure FTP daemon的缩写,安全性是它的一个最大的特点。虚拟用户是指在FT...

linux vsftpd 创建虚拟用户 过程记录

之前用系统账户作为ftp的登录账户,比较不安全,改用虚拟账户。步骤如下:   1.安装vsftpd、db_load,省略 2.在一个目录创建一个用户名密码文件,比如 [plain] vi...

vsftpd虚拟用户的配置

  • 2017-08-08 10:35
  • 33KB
  • 下载

vsftpd服务器-匿名-本地-虚拟用户

vsftpd配置文件的帮助:      man   vsftpd.conf lftp:是Linux中专有的命令:所以推荐使用      lftp  -u  user1 ...

建立Vsftpd虚拟用户

  • 2012-01-19 10:58
  • 17KB
  • 下载

vsftpd 安装与虚拟用户配置

vsftpd 安装与虚拟用户配置 作者:守住每一天 blog:www.opendoc.com.cn bbs:bbs.linuxtone.org 感谢:兄弟张志坚...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)