【第22期】观点:IT 行业加班,到底有没有价值?

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 ~]# 
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

马哥门徒网络班二期报名

了解全部内容详情请点击----->  马哥门徒 说明: 1、本课程全程会交叉使用RHEL5.8或CentOS5.8,以及RHEL6.4或CentOS6.4;然而...

深入浅出 Linux Vsftpd 创建多虚拟用户教程

Vsftpd 是一款轻量级并有着安全与简易等特性的FTP服务器程序,破受欢迎。在 Linux 中一旦配置好 Vsftpd  环境就可以一劳永逸,任意的迁移到类似的服务器之上,因此我们对配置过程做个系统的了解也是有必要的。 本 文的任务是...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

LNS-读书笔记

第一章:基本网络配置一、查看及测试网络配置1.查看网络接口信息   ifconfig   [-a]  [接口名]     -a  查看所有接口,不论接口是否活跃   [接口名] 只显指定接口2.测试网...

vsftpd创建虚拟用户的步聚

一、创建虚拟用户的步骤: 1.创建虚拟用户的口令文件(奇数行是用户名,偶数行是用户名的密码) #cat logins.txt zhang3 123 li4 456 2.使用db_load生成vsftpd的认证文件 #db_load -T -t hash -f logins.txt /...

Linux学习内容--我认为已经足够了

一、Linux系统基础及系统管理 1、操作系统发展史,系统架构平台概览; Linux起源、理念、发展历史及各发行版; 2、Linux基础知识、基本命令、获得使用帮助及文件系统组织结构等; ...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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