01000001
01000001

Reputation: 873

Generate random passwords in shell with one special character

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

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

then putting length as

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

but got no positive result.

Upvotes: 6

Views: 14348

Answers (2)

elpidio.valdes
elpidio.valdes

Reputation: 5

## Objective: Generating Random Password:
function random_password () {
    [[ ${#1} -gt 0 ]] && { local length=${1}; } || { local length=16; }
    export DEFAULT_PASSWORDLENGTH=${length};
    export LC_CTYPE=C;
    local random="$(
        tr -cd "[:graph:]" < /dev/urandom \
        | head -c ${length} \
        | sed -e 's|\`|~|g' \
              -e 's|\$(|\\$(|g';
      )";
    echo -e "${random}";
    return 0;
  }; alias random-password='random_password';

$ random-password 32 ;
)W@j*deZ2#eMuhU4TODO&eu&r)&.#~3F

# Warning: Do not consider these other options

# date +%s | sha256sum | base64 | head -c 32 | xargs -0;
# Output: MGFjNDlhMTE2ZWJjOTI4OGI4ZTFiZmEz

# dd if=/dev/urandom count=200 bs=1 2>/dev/null \
# | tr -cd "[:graph:]" \
# | cut -c-${length} \
# | xargs -0;
# Output: AuS*D=!wkHR.4DZ_la

Upvotes: 0

choroba
choroba

Reputation: 241918

#! /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 prevents characters like ř from appearing.
  • grep -o outputs just the matching substring, i.e. a single character.
  • shuf shuffles the lines. I originally used sort -R, but it kept the same characters together (ff1@22MvbcAA).

Upvotes: 11

Related Questions