在shell中使用一个特殊字符生成随机密码 [英] Generate random passwords in shell with one special character
本文介绍了在shell中使用一个特殊字符生成随机密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
</dev/urandom tr -dc 'A-Za-z0-9@#$%&_+=' | head -c 16
这将完美地随机生成密码.
which is randomly generating passwords perfectly.
我想要两个更改:
- 它只能包含上面列出的一个特殊字符
- 它应该选择一个随机长度
我尝试过length = $(($RANDOM%8+9))
然后将长度设为
</dev/urandom tr -dc 'A-Za-z0-9@#$%&_+=' | head -c$length
但没有得到积极的结果.
but got no positive result.
推荐答案
#! /bin/bash
chars='@#$%&_+='
{ </dev/urandom LC_ALL=C grep -ao '[A-Za-z0-9]' \
| head -n$((RANDOM % 8 + 9))
echo ${chars:$((RANDOM % ${#chars})):1} # Random special char.
} \
| shuf \
| tr -d '\n'
-
LC_ALL=C
防止出现诸如ř之类的字符. -
grep -o
仅输出匹配的子字符串,即单个字符. -
shuf
随机排列各行.我最初使用sort -R
,但是将相同的字符保持在一起(ff1@22MvbcAA
). LC_ALL=C
prevents characters like ř from appearing.grep -o
outputs just the matching substring, i.e. a single character.shuf
shuffles the lines. I originally usedsort -R
, but it kept the same characters together (ff1@22MvbcAA
).
这篇关于在shell中使用一个特殊字符生成随机密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文