Random Strings and Password Generator

Python 3: secrets module

string module

$ python3
>>> import string

>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

>>> string.capwords('hello world')
'Hello World'

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>> string.digits
'0123456789'

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

>>> string.whitespace
' \t\n\r\x0b\x0c' 

>>> len(string.whitespace + string.digits + string.ascii_letters + string.punctuation)
100

>>> len(string.printable)
100

secrets module

See: https://docs.python.org/3/library/secrets.html

>>> import secrets

>>> ''.join(secrets.choice(''.join(set(string.printable) - set(string.whitespace))) for i in range(32))
'\rg@P_Jb\WyRW[n$GVM(qjZoCfJ48*(d'

>>> alphabet = string.ascii_letters + string.digits
>>> while True:
…     password = ''.join(secrets.choice(alphabet) for i in range(10))
…     if (any(c.islower() for c in password)
…             and any(c.isupper() for c in password)
…             and sum(c.isdigit() for c in password) >= 3):
…         break

>>> password
'N4Ur7yq99B'

Random Strings for Bash

For macOS, add env LC_ALL=C to avoid error: tr: Illegal byte sequence

$ tr -cd "[:alnum:]" < /dev/urandom | head -c 12
boIqf8FNkXXj

$ tr -cd "[:lower:][:digit:]" < /dev/urandom | head -c 12
1jemmxwkoy2v

$ tr -cd "[:digit:]" < /dev/urandom | head -c 10
4392078854

$ env LC_ALL=C tr -cd "[:digit:][:upper:]" < /dev/urandom | head -c 20
50C7EUZGYR5AOPDZO7IO
$ man tr
TR(1)                     BSD General Commands Manual                    TR(1)

NAME
     tr -- translate characters

SYNOPSIS
     tr [-Ccsu] string1 string2
     tr [-Ccu] -d string1
     tr [-Ccu] -s string1
     tr [-Ccu] -ds string1 string2

DESCRIPTION
     The tr utility copies the standard input to the standard output with substitution or deletion of
     selected characters.

     The following options are available:

     -C      Complement the set of characters in string1, that is ``-C ab'' includes every character except
             for `a' and `b'.

     -c      Same as -C but complement the set of values in string1.

     -d      Delete characters in string1 from the input.

     -s      Squeeze multiple occurrences of the characters listed in the last operand (either string1 or
             string2) in the input into a single instance of the character.  This occurs after all deletion
             and translation is completed.

     -u      Guarantee that any output is unbuffered.

In the first synopsis form, the characters in string1 are translated into the characters in string2
     where the first character in string1 is translated into the first character in string2 and so on.  If
     string1 is longer than string2, the last character found in string2 is duplicated until string1 is
     exhausted.

     In the second synopsis form, the characters in string1 are deleted from the input.

     In the third synopsis form, the characters in string1 are compressed as described for the -s option.

     In the fourth synopsis form, the characters in string1 are deleted from the input, and the characters
     in string2 are compressed as described for the -s option.

     The following conventions can be used in string1 and string2 to specify sets of characters:

     character  Any character not described by one of the following conventions represents itself.

     \octal     A backslash followed by 1, 2 or 3 octal digits represents a character with that encoded
                value.  To follow an octal sequence with a digit as a character, left zero-pad the octal
                sequence to the full 3 octal digits.

    \character
                A backslash followed by certain special characters maps to special values.

                \a    <alert character>
                \b    <backspace>
                \f    <form-feed>
                \n    <newline>
                \r    <carriage return>
                \t    <tab>
                \v    <vertical tab>

                A backslash followed by any other character maps to that character.

     c-c        For non-octal range endpoints represents the range of characters between the range end-
                points, inclusive, in ascending order, as defined by the collation sequence.  If either or
                both of the range endpoints are octal sequences, it represents the range of specific coded
                values between the range endpoints, inclusive.

...

     [:class:]  Represents all characters belonging to the defined character class.  Class names are:

                alnum        <alphanumeric characters>
                alpha        <alphabetic characters>
                blank        <whitespace characters>
                cntrl        <control characters>
                digit        <numeric characters>
                graph        <graphic characters>
                ideogram     <ideographic characters>
                lower        <lower-case alphabetic characters>
                phonogram    <phonographic characters>
                print        <printable characters>
                punct        <punctuation characters>
                rune         <valid characters>
                space        <space characters>
                special      <special characters>
                upper        <upper-case characters>
                xdigit       <hexadecimal characters>

                When ``[:lower:]'' appears in string1 and ``[:upper:]'' appears in the same relative posi-
                tion in string2, it represents the characters pairs from the toupper mapping in the LC_CTYPE
                category of the current locale.  When ``[:upper:]'' appears in string1 and ``[:lower:]''
                appears in the same relative position in string2, it represents the characters pairs from
                the tolower mapping in the LC_CTYPE category of the current locale.

                With the exception of case conversion, characters in the classes are in unspecified order.

                For specific information as to which ASCII characters are included in these classes, see
                ctype(3) and related manual pages.

     [=equiv=]  Represents all characters belonging to the same equivalence class as equiv, ordered by their
                encoded values.

     [#*n]      Represents n repeated occurrences of the character represented by #.  This expression is
                only valid when it occurs in string2.  If n is omitted or is zero, it is be interpreted as
                large enough to extend string2 sequence to the length of string1.  If n has a leading zero,
                it is interpreted as an octal value, otherwise, it is interpreted as a decimal value.

ENVIRONMENT
     The LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect the execution of tr as described
     in environ(7).

EXIT STATUS
     The tr utility exits 0 on success, and >0 if an error occurs.

EXAMPLES
     The following examples are shown as given to the shell:

     Create a list of the words in file1, one per line, where a word is taken to be a maximal string of let-
     ters.

           tr -cs "[:alpha:]" "\n" > file1

     Translate the contents of file1 to upper-case.

           tr "[:lower:]" "[:upper:]" > file1

     (This should be preferred over the traditional UNIX idiom of ``tr a-z A-Z'', since it works correctly
     in all locales.)

     Strip out non-printable characters from file1.

           tr -cd "[:print:]" > file1

     Remove diacritical marks from all accented variants of the letter `e':

           tr "[=e=]" "e"

Example

$ tldr tr
  tr

  Translate characters: run replacements based on single characters and character sets.

  - Replace all occurrences of a character in a file, and print the result:
    tr find_character replace_character < filename

  - Replace all occurrences of a character from another command's output:
    echo text | tr find_character replace_character

  - Map each character of the first set to the corresponding character of the second set:
    tr 'abcd' 'jkmn' < filename

  - Delete all occurrences of the specified set of characters from the input:
    tr -d 'input_characters' < filename

  - Compress a series of identical characters to a single character:
    tr -s 'input_characters' < filename

  - Translate the contents of a file to upper-case:
    tr "[:lower:]" "[:upper:]" < filename

  - Strip out non-printable characters from a file:
    tr -cd "[:print:]" < filename

Strong Password with tr and /dev/urandom

For macOS, add env LC_ALL=C to avoid error: tr: Illegal byte sequence

$ tr -cd "[:print:]" < /dev/urandom | tr -d "[:blank:]" | head -c 32
m5.egq+[7bEb_\B|Iv`9}zftF>^i\O=

$ env LC_ALL=C tr -cd "[:print:]" < /dev/urandom | tr -d "[:blank:]" | head -c 32
NST5$^X72F2q~-&a#Q)?$HeO%sv'vWvD
$ pwgen -sync 32 1
 Q{:5\D%S8{I!O_h<G-\Hgh)9a=}H71zh

$ pwgen -h
 Usage: pwgen [ OPTIONS ] [ pw_length ] [ num_pw ]
 Options supported by pwgen:
   -c or --capitalize
     Include at least one capital letter in the password
   -A or --no-capitalize
     Don't include capital letters in the password
   -n or --numerals
     Include at least one number in the password
   -0 or --no-numerals
     Don't include numbers in the password
   -y or --symbols
     Include at least one special symbol in the password
   -r  or --remove-chars=
     Remove characters from the set of characters to generate passwords
   -s or --secure
     Generate completely random passwords
   -B or --ambiguous
     Don't include ambiguous characters in the password
   -h or --help
     Print a help message
   -H or --sha1=path/to/file[#seed]
     Use sha1 hash of given file as a (not so) random generator
   -C
     Print the generated passwords in columns
   -1
     Don't print the generated passwords in columns
   -v or --no-vowels
     Do not use any vowels so as to avoid accidental nasty words

Also see: https://gist.github.com/earthgecko/3089509

Leave a Comment

Your email address will not be published.

ten + 8 =