1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
| #!/usr/bin/python
#-*- coding:utf-8 -*
#django添加数据库用户密码
import sys
import os
from optparse import OptionParser
os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "mysite.settings" )
from accounts.models import User
import hashlib
###编码转移,可以输出中文####
reload(sys)
sys.setdefaultencoding('utf-8')
###%prog表示脚本本身
MSG_USAGE = "%prog [ -u <username>][-p <password>][-t <user_type>][-h <help>]"
MSG_VERSION = "%prog 20140529"
###usage打印用法,version输出版本信息
optParser = OptionParser(usage=MSG_USAGE,version=MSG_VERSION)
###对optParser增加选项
optParser.add_option("-u","--username",action = "store",type = "string",dest = "UserName",help="添加数据库用户名(必填)")
optParser.add_option("-p","--password",action = "store",type = "string",dest = "Password",help="添加数据库密码(必填)")
optParser.add_option("-t","--user_type",action = "store",type = "string",dest = "User_Type",default="1",help="添加用户权限,0为管理员,1为普通,默认为1")
#fakeArgs = ['-u','leon','-p','123456','-t','a']
options,args = optParser.parse_args()
TYPE = options.User_Type
USERNAME = options.UserName
PASSWORD = options.Password
#User_Type返回不是1或者0则退出
if TYPE not in ('1','0'):
optParser.print_help()
sys.exit(1)
#判断参数-u,-p是否为空,返回帮助
args_list = [USERNAME,PASSWORD]
for i in args_list:
if i is None:
print '请使用(-h,--help)来获得帮助'
sys.exit(0)
#User是在accounts中models.py的类,定义了数据库的一些信息,插入用户
#判断用户是否存在
def init():
CHECK_NAME=User.objects.filter(name=USERNAME)
if len(CHECK_NAME) > 0:
print "%s 用户已经存在" % USERNAME
else:
u = User(name=USERNAME, password=hashlib.md5(PASSWORD).hexdigest(), user_type=TYPE)
u.save()
if '__main__' == __name__:
init()
|