通过随机random 和MD5两种方式生成,写入本地并且保存在数据库
import random
import string
import hashlib
import time
import pymysql
import re
import sys
def main():
key = input('请选择激活码生成方式:\n选择random方法请按0 ;\n选择hash md5方法请按1 ;\n退出请按q->')
if key == str(1):
codes = str(get_idcode())
with open("md5_code.txt", "w", encoding='utf-8') as f:
f.write(codes)
stra = str(get_idcode().keys()) # dict_keys(['1023DF3EB90710731A39BF84E5EF2AD6'])
strb = str(get_idcode().values())
code = re.split(r'\'',stra)[1] # 正则提取字符串部分
timestrap = re.split(r'\'', strb)[1]
sql = which_table(1,code,timestrap)
conn_mysql(sql)
print('\nsuccessful')
elif key == str(0):
# print(chars)
start_time = time.time()
codes = [create_ticket() for i in range(1, 21)] # 一次生成20个
with open("random_code.txt", "w", encoding='utf-8') as f:
f.write(str(codes).replace('[', '').replace(']', ''))
i = 1
while (i <= 20):
stra = str(create_ticket().keys())
# print(stra)
strb = str(create_ticket().values())
code = re.split(r'\'', stra)[1]
# print(code)
timestrap = re.split(r'\'', strb)[1]
sql = which_table(0, code, timestrap)
conn_mysql(sql)
i += 1
print('\nsuccessful')
end_time = time.time()
use_time = end_time - start_time
print('random-耗时{:.4f}秒'.format(use_time)) # 一口气记录二十条有点久 加个计时看看耗时情况
elif key == 'q':
sys.exit()
else: # 容错处理
print('输入有误,请重试')
print('-*'*20)
main() # 输入错误则重新执行
# 生成随机激活码
def create_ticket():
chars = string.ascii_uppercase + string.digits # 大写字母和数字的字符串集合
code = random.choices(chars, k=16) # 从chars随机生成16位的激活码
# print(type(code)) # <class 'list'>
str_code = ''.join(code) # 列表转字符串
create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # strftime定义时间显示样式
x = {str_code:create_time} # 拼接成字典
return x
# 生成唯一的激活码 MD5
def get_idcode():
account = 'l2279387573' # 模拟用户账号
now = round(time.time()) # 四舍五入一下 不需要小数点
str_code = str(now)+account # 字符串拼接
hash_md5 = hashlib.md5() # 开始哈希
hash_md5.update(str_code.encode('utf-8'))
upper_code = hash_md5.hexdigest().upper() # 将md5加密后的值upper后赋给变量 upper_code
create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # strftime定义时间显示样式
dict = {upper_code:create_time} # 将upper_code,create_time拼接成字典返回出去
return dict
# 连接mysql数据库
def conn_mysql(sql):
db = pymysql.connect(host='localhost',
port=3306,
user='写自己的',
password='写自己的',
db='写自己的',
)
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
# 通过用户输入 选择不同的SQL语句,主要是为了插入到不同的表
def which_table(num,a,b):
if num == 0:
sql = "insert into random_table (activation_code,create_date) values ('%s','%s')"%(a,b)
elif num ==1:
sql = "insert into md5_table (activation_code,create_date) values ('%s','%s')"%(a,b)
return sql
if __name__ == "__main__":
main()