在python中生成密码

我想在python中生成一些字母数字密码。 一些可能的方法是:

import string

from random import sample, choice

chars = string.letters + string.digits

length = 8

''.join(sample(chars,length)) # way 1

''.join([choice(chars) for i in range(length)]) # way 2

但我不喜欢这两者,因为:

方法1仅选择唯一字符,并且您不能生成长度> len(字符)的密码

方式2我们有''.join(choice(chars) for _ in xrange(length))变量未使用,我找不到很好的方法来避免这种情况

那么,还有其他好的选择吗?

附言 因此,我们在这里进行了''.join(choice(chars) for _ in xrange(length))的100000次迭代测试:

''.join(sample(chars,length)) # way 1; 2.5 seconds

''.join([choice(chars) for i in range(length)]) # way 2; 1.8 seconds (optimizer helps?)

''.join(choice(chars) for _ in range(length)) # way 3; 1.8 seconds

''.join(choice(chars) for _ in xrange(length)) # way 4; 1.73 seconds

''.join(map(lambda x: random.choice(chars), range(length))) # way 5; 2.27 seconds

因此,获胜者是''.join(choice(chars) for _ in xrange(length))。

7个解决方案

89 votes

从Python 3.6开始

您应该使用secrets模块来生成密码安全的密码,该密码可从Python 3.6开始使用。 改编自文档:

import secrets

import string

alphabet = string.ascii_letters + string.digits

password = ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password

gerrit answered 2020-06-29T17:20:12Z

33 votes

对于在那里的加密PRNG人士:

def generate_temp_password(length):

if not isinstance(length, int) or length < 8:

raise ValueError("temp password must have positive length")

chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"

from os import urandom

return "".join(chars[ord(c) % len(chars)] for c in urandom(length))

请注意,对于均匀分布,chars的字符串长度应为128的整数除数; 否则,您将需要一种不同的方法来从空间中统一选择。

Ben Mosher answered 2020-06-29T17:20:37Z

13 votes

警告由于严重的安全问题,应忽略此答案!

选项2似乎很合理,除了您可以添加一些改进:

''.join(choice(chars) for _ in range(length)) # in py2k use xrange

_是常规的“我不在乎里面有什么”变量。 而且您不需要列表理解,生成器表达式对于str.join来说也很好。如果唯一的正确方法,还不清楚“慢”是什么意思。

SilentGhost answered 2020-06-29T17:21:07Z

5 votes

我认为这可以解决问题。 random.SystemRandom使用与os.urandom相同的底层加密随机函数,但使用熟悉的random接口。 这个函数不会像Ben的答案那样受制于128字节的怪异事物。

import random

import string

def gen_random_string(char_set, length):

if not hasattr(gen_random_string, "rng"):

gen_random_string.rng = random.SystemRandom() # Create a static variable

return ''.join([ gen_random_string.rng.choice(char_set) for _ in xrange(length) ])

password_charset = string.ascii_letters + string.digits

gen_random_string(password_charset, 32)

Tim Ludwinski answered 2020-06-29T17:21:27Z

4 votes

对于那些卡在python <3.6上的人,我建议以下内容:

import os, math, string, struct

def generate_password(pass_len):

symbols = string.printable.strip()

return ''.join([symbols[x * len(symbols) / 256] for x in struct.unpack('%dB' % (pass_len,), os.urandom(pass_len))])

与本·莫舍(Ben Mosher)的解决方案相比,它的优势在于,符号中的每个符号发生的变化均等,而使用模数则稍微有利于字母中的第一个符号。 在此建议中,符号字母也较大。

gardarh answered 2020-06-29T17:21:52Z

-4 votes

我写了自己喜好的脚本,主要是为了避免抄写和记忆时出错。 (例如:删除有些模棱两可且没有重复的字符。)

import optparse

import os

import random

import sys

DEFAULT_CHARS = "234679ADEFGHJKLMNPRTUWabdefghijkmnpqrstuwy"

DEFAULT_LEN = 18

def choices(options, length, choice=random.choice):

return (choice(options) for _ in xrange(length))

def choices_non_repeated(options, length, choice=random.choice):

assert len(options) > 1

last = choice(options)

count = 0

while count < length:

yield last

count += 1

while True:

value = choice(options)

if value != last:

last = value

break

def main(args):

op = optparse.OptionParser(add_help_option=False)

op.add_option("--help", action="help",

help="show help message and exit")

op.add_option("-b", "--bare", action="store_true", default=False,

help="print passwords without trailing newline")

op.add_option("-c", "--chars", metavar="SET", nargs=1, default=DEFAULT_CHARS,

help="character set to use (default: %default)")

op.add_option("--repeat", action="store_true", default=False,

help="allow repetition")

op.add_option("-l", "--len", dest="max", nargs=1, type="int", default=DEFAULT_LEN,

help="max length (default: %default)")

op.add_option("--min", nargs=1, type="int", default=None,

help="min length (defaults to max)")

op.add_option("-n", "--count", nargs=1, type="int", default=None,

help="number of passwords to generate (default: %default)")

op.add_option("--cols", type="int", default=None,

help="number of columns to use")

opts, args = op.parse_args(args)

if args:

op.error("unknown arguments")

if os.isatty(sys.stdin.fileno()) and (

opts.count is None and opts.cols is None

and not opts.bare

):

opts.cols = 80 // (opts.max + 1)

opts.count = opts.cols * 25

else:

if opts.count is None:

opts.count = 1

if opts.cols is None:

opts.cols = 1

if opts.bare and opts.cols != 1:

op.error("bare output requires --cols=1")

if opts.min == None:

opts.min = opts.max

if any(x < 1 for x in [opts.cols, opts.count, opts.min, opts.max]):

op.error("values must be >= 1")

choices_func = choices_non_repeated

if opts.repeat:

choices_func = choices

elif len(set(opts.chars)) < 2:

op.error("must allow repetition or provide a longer character set")

return "op.error shouldn't return"

col = 0

for _ in xrange(opts.count):

length = random.randint(opts.min, opts.max)

password = "".join(choices_func(opts.chars, length))

sys.stdout.write(password)

if not opts.bare:

col += 1

if col == opts.cols:

sys.stdout.write("\n")

col = 0

else:

sys.stdout.write(" ")

if __name__ == "__main__":

sys.exit(main(sys.argv[1:]))

answered 2020-06-29T17:22:12Z

-4 votes

您可能要使用map而不是列表推导:

''.join(map(lambda x: random.choice(chars), range(length)))

Sergey Stolyarov answered 2020-06-29T17:22:32Z

在python中设置密码登录_在python中生成密码相关推荐

  1. 在python中设置密码登录_如何从python脚本在linux中设置用户密码?

    我正在尝试自动设置SFTP访问.此脚本作为具有sudo权限且没有密码的用户运行. 我可以像这样创建一个用户: >>> import subprocess >>> p ...

  2. python实现qq登录_在django中实现QQ登录

    在服务器端做qq登录的流程: 1.放置QQ登录按钮,这个去QQ的网站上下,把这个按钮的连接指向 https://graph.qq.com/oauth2.0/authorize?response_typ ...

  3. python itchat 无法登录_利用python实现在微信群刷屏的方法

    hello,我是小小炽,这是我写的第一篇博客,写博客一直都想在写,但是苦于能力尚浅,在各位大牛面前那既然是关公面前耍大刀了,但是其实想来每一个大牛不也是从一个小白慢慢进步学习从而达到一定的高度的吗,而 ...

  4. 用python写注册登录_用Python实现web端用户登录和注册功能的教程

    用户管理是绝大部分Web网站都需要解决的问题.用户管理涉及到用户注册和登录. 用户注册相对简单,我们可以先通过API把用户注册这个功能实现了: _RE_MD5 = re.compile(r'^[0-9 ...

  5. python做excel宏_利用Python 开发 Excel 宏脚本的神器!

    今天介绍一个叫 xlpython 的库,通过它我们可以用 Python 来开发 Excel 的宏脚本,真正实现在 Excel 中调用 Python. 基本环境 操作系统:Windows 10 x64 ...

  6. python调用excel宏_用Python如何开发Excel宏脚本?新手必学

    今天介绍一个叫 xlpython 的库,通过它我们可以用 Python 来开发 Excel 的宏脚本,真正实现在 Excel 中调用 Python. 基本环境 操作系统:Windows 10 x64 ...

  7. python 通过title判断_利用Python模拟GitHub登录

    点击关注,我们共同每天进步一点点! 最近学习了Fiddler抓包工具的简单使用,通过抓包,我们可以抓取到HTTP请求,并对其进行分析.现在我准备尝试着结合Python来模拟GitHub登录. Fidd ...

  8. python 打印数组变量_使用Python将数组的元素导出到变量中(unpacking)

    下面就为大家分享一篇使用Python将数组的元素导出到变量中(unpacking),具有很好的参考价值,希望对大家有所帮助.一起过来看看吧 最近工作中遇到一个问题,需要利用Python将数组(list ...

  9. python之禅 中文_《Python之禅》中对于Python编程过程中的一些建议

    <Python之禅>中对于Python编程过程中的一些建议 来源:中文源码网    浏览: 次    日期:2018年9月2日 [下载文档:  <Python之禅>中对于Pyt ...

最新文章

  1. Python常用函数--文档字符串DocStrings
  2. 代码中应用设计模式,看这一篇就够了
  3. mysql 的select语句_MySQLSELECT语句_MySQL
  4. 在html中三个图片切换,轻松搞定网页中的图片切换
  5. discuz设置用户每天回帖数_discuz回贴通知插件实现-显示用户状态设置
  6. 《论文笔记》Cooperative Multi-Robot Monocular-SLAM using Salient Landmarks
  7. 8266不通过usb供电_HomePod mini?电源线同样不可拆卸:但或能用USB-C移动电源供电...
  8. vue 表单 input checkbox
  9. mysql错误Table ‘./mysql/proc’ is marked as crashed and should be repaired
  10. Makefile文件(六)_使用条件判断
  11. isql连接sybase_使用isql连接Sybase ASE数据库的常见错误及处理方式
  12. 帝国CMS7.5忘记后台密码怎么找回
  13. 机器学习的数学基础(2):赋范空间、内积空间、完备空间与希尔伯特空间
  14. 如何整合线上和线下营销进行深度交融
  15. ARM学习笔记--day10
  16. 计算机网络学习笔记<一>|工作必备|银行科技岗面试|内附八股面经|秋招提前批冲冲冲
  17. 计算机桌面图标突然都不见了怎么办,电脑桌面图标都没了怎么办 桌面图标消失找回方法【图文】...
  18. java生成以及解析二维码
  19. Web渗透工程师零基础就业班【从入门到就业】
  20. 开关电源EMI整改经验总结

热门文章

  1. oracle拼接空格错误,oracle运维故事 一个空格引发的血案
  2. subtext3php,sublime text3怎么快速查找和替换?快捷键是什么
  3. docker 数据卷 mysql_Docker 入门教程(五)数据卷 Volumes
  4. 不搞虚的!快速把你拉入Docker 的门里
  5. Maven私服(二) - Nexus的安装
  6. hql查询过滤器及相关聚合函数查询详解
  7. php安装mongo扩展,php安装mongo扩展和mongodb扩展
  8. VMware上安装Linux镜像CentOS
  9. 基于JAVA+SpringMVC+MYSQL的城市公交查询系统
  10. springboot项目报错JedisConnectionException: Could not get a resource from the pool