利用Python如何生成随机密码

yipeiwu_com7年前Python基础

本位实例为大家分享了Python生成随机密码的实现过程,供大家参考,具体内容如下

写了个程序,主要是用来检测MySQL数据库的空密码和弱密码的,

在这里,定义了三类弱密码:

1. 连续数字,譬如123456,在get_weak_num中实现

2. 连续字母,譬如abcdef,在get_weak_character中实现

当然,个数都是随机的。

3. 数字和字母随机组合。在get_weak_num_character中实现。

同时定义了一个password_exist的列表,用于保存不同的密码。如果新生成的密码在列表中存在,则不进行MySQL数据库的连接,直接到下一次循环。

具体如下:

#coding=utf8
import random,string,MySQLdb
def get_num():
  return random.randint(0,9)
def get_char():
  return random.choice(tuple(string.lowercase))
def choose_any():
  return [str(get_num()),get_char()]
def get_weak_num():
  weak_num=[]
  initial_num=get_num()
  for i in range(get_num()):
    weak_num.append(str(initial_num+i))
    if initial_num +i ==9:
      break;
  return weak_num
def get_weak_character():
  weak_character=[]
  initial_character=get_char()
  for i in range(get_num()):
    weak_character.append(chr(ord(initial_character)+i))
    if chr(ord(initial_character)+i) == 'z':
      break
  return weak_character
def get_weak_num_character():
  return [random.choice(choose_any()) for num in range(get_num())]
password_exist=[]
for i in range(10000):
  choice = [get_weak_num(), get_weak_character(), get_weak_num_character()]
  password=''.join(random.choice(choice))
  print "第"+str(i)+"次密码为:"+password
  if password in password_exist:
    continue
  else:
    try:
      MySQLdb.connect('192.168.244.145', 'root', password)
      print 'The password for MySQL is:'+password
      break
    except:
      continue
    password_exist.append(password)
if i == 9999:
  print 'The password is not so weak~'

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关文章

用Python做的数学四则运算_算术口算练习程序(后添加减乘除)

最近着迷上了 Python 用Python给小宝做的数学算数口算练习程序(2015年1月添加四则运算)! 给小宝做的口算游戏: #用Python给小宝做的数学算数口算练习程序(201...

python实现学生管理系统

python实现学生管理系统

python写的简单的学生管理系统,练习python语法。 可以运行在windows和linux下,python 2.7。 #!/usr/local/bin/python #...

python3使用urllib示例取googletranslate(谷歌翻译)

复制代码 代码如下:#!/usr/bin/env python3# -*- coding: utf-8 -*-# File Name : gt1.py# Purpose :# Creat...

Python中时间datetime的处理与转换用法总结

python中日期类datetime功能比较强大,使用起来很方便,把常用的两种用法总结如下: from datetime import datetime from datetime...

python获取图片颜色信息的方法

本文实例讲述了python获取图片颜色信息的方法。分享给大家供大家参考。具体分析如下: python的pil模块可以从图片获得图片每个像素点的颜色信息,下面的代码演示了如何获取图片所有点...