bash 使用一个特殊字符在 shell 中生成随机密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30947873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:14:34  来源:igfitidea点击:

Generate random passwords in shell with one special character

bashshellunixrandompasswords

提问by 01000001

I have the following code:

我有以下代码:

</dev/urandom tr -dc 'A-Za-z0-9@#$%&_+=' | head -c 16

which is randomly generating passwords perfectly.

这是完美的随机生成密码。

I want two changes:

我想要两个改变:

  1. It should only contain one special character listed above
  2. It should choose a random length
  1. 它应该只包含上面列出的一个特殊字符
  2. 它应该选择一个随机长度

I tried with length = $(($RANDOM%8+9))

我试过 length = $(($RANDOM%8+9))

then putting length as

然后把长度作为

</dev/urandom tr -dc 'A-Za-z0-9@#$%&_+=' | head -c$length

but got no positive result.

但没有得到积极的结果。

回答by choroba

#! /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=Cprevents characters like ? from appearing.
  • grep -ooutputs just the matching substring, i.e. a single character.
  • shufshuffles the lines. I originally used sort -R, but it kept the same characters together (ff1@22MvbcAA).
  • LC_ALL=C防止像 ? 从出现。
  • grep -o只输出匹配的子串,即单个字符。
  • shuf打乱线条。我最初使用的是sort -R,但它保留了相同的字符 ( ff1@22MvbcAA)。