生成随机密码脚本,用python和bash两种方法实现

2018-06-25 21次浏览 发表评论

bash方法:

vim pwd.sh
#!/bin/bash

[ -n "$1" ] && length=$1 || length=8
chars='abcdefghijkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ1234567890'
charsLength=`echo $chars | wc -m`

pw=''
for ((i=0; i<$length; i++)); do

  r=`echo $RANDOM/32767 | bc -l`
  num=`echo "$r*$charsLength" | bc`
  pw=$pw`echo $chars | cut -c$((${num%.*}+1))`

done
echo $pw

生成一个30个字符的密码:

./pwd.sh 30
5tDwTVb3REkzpUaBcYGG395JSmCsnh    

python方法:

vim pwd.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import string

def pwd(length=8):
    chars = set(string.ascii_letters + string.digits)
    return ''.join([i for i in chars][0:length])

if __name__ == "__main__":
    print(pwd(30))

同样生成一个30字符的密码:

./pwd.py
hTiecwDPAdK307XQrRuSBG9HpsYovF

速度比较:

time ./pwd.py
cFERSmdGQJMNej9oHzBk8ipyObhqA6

real    0m0.022s
user    0m0.017s
sys     0m0.004s
time ./pwd.sh 30
EdmZCRBjxTAmmjNP4SdEEhpa66b5P

real    0m0.188s
user    0m0.105s
sys     0m0.079s

可以看出python的执行速度比bash快出很多!

评论

随便说点,聊聊天~