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

vsftpd配置虚拟用户为登录用户

vsftpd配置虚拟用户为登录用户
  • zhangpfly
  • zhangpfly
  • 2017年06月13日 09:13
  • 691

CentOS 6.5系统安装vsFTPd并配置虚拟用户

转:http://www.server110.com/vsftpd/201403/8169.html 在LINUX上要使用FPT服务,那就一定要学会vsftpd的配置和安装,vsftpd是Linux...
  • lcathm
  • lcathm
  • 2015年09月09日 10:54
  • 4141

Vsftpd虚拟用户配置

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明 http://blog.csdn.net/wenshuangzhu/article/details/44078949 ...
  • wenshuangzhu
  • wenshuangzhu
  • 2015年03月05日 10:21
  • 5176

vsftp配置虚拟用户

vsftp配置虚拟用户 1、vsftp安装 由于系统是debian7,故直接通过apt-get来安装就行了。 sudo apt-get install vsftpd 2、...
  • CatEatApple
  • CatEatApple
  • 2016年04月06日 16:56
  • 1037

vsftpd虚拟用户配置【虚拟用户映射到系统账号vuser{禁止该账户登录}登录ftp】

文章来源: http://www.cnblogs.com/wubz/archive/2012/04/15/2450421.html vsftpd虚拟用户配置 Vsftpd虚拟用户...
  • buster2014
  • buster2014
  • 2016年02月28日 19:39
  • 770

Linux下vsftpd虚拟账号追加

本来Linux菜鸟一枚,最近项目中有用到对ftp的操作,无奈身边一穷二白,什么都需要从头开始,各种百度和查询资料,千辛万苦,排除万难。终于搭建好服务,顺利访问。 现总结一二,以备不时之需。 前言: 首...
  • u014251190
  • u014251190
  • 2014年03月20日 21:34
  • 1080

CentOS 6.6 下安装vsftpd并配置虚拟用户

本文转载自网络http://www.jb51.net/os/RedHat/112444.html, 本人配置的OS版本为centos 6.6 ----------------------------...
  • gonedays
  • gonedays
  • 2015年07月30日 11:42
  • 1081

vsFTP配置总结之虚拟用户及权限管控

1 需求 为了保证系统的安全性,现对系统中vsftpd服务进行调整,主要为禁止OS本地账户直接登录,采用虚拟账户;设置两个虚拟账户,一个用于上传更新(可读可写),一个用于下载(仅读);ftp根目...
  • u011457628
  • u011457628
  • 2014年02月14日 17:47
  • 6869

vsftp虚拟用户权限设置

首先安装vsftp db-4 斯蒂芬个http://hi.baidu.com/phpfool/item/d295fd5f6f960e3d33e0a981 mkdir -p /opt/ftp 创建用户 ...
  • feiniu5566
  • feiniu5566
  • 2013年10月30日 11:55
  • 1113

centos7下vsftp服务设置虚拟用户

1、安装 vsftpd服务 2、创建用于作为虚拟账号的系统账号 useradd-d/home/ftpsite virtual_user  chmod700/home/ftpsite  这个...
  • lda_ming
  • lda_ming
  • 2017年04月01日 16:47
  • 1317
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Python创建、删除、查询vsftpd的虚拟用户(虚拟用户使用MySQL数据库)
举报原因:
原因补充:

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