code: def secure_password(length=20, use_random=True):
      '''
      Generate a secure password.
      '''
      try:
          length = int(length)
          pw = ''
          while len(pw) < length:
              if HAS_RANDOM and use_random:
                  while True:
                      try:
                          char = salt.utils.stringutils.to_str(get_random_bytes(1))
                          break
                      except UnicodeDecodeError:
                          continue
                  pw += re.sub(
                      salt.utils.stringutils.to_str(r'\W'),
                      str(),  # future lint: disable=blacklisted-function
                      char
                  )
              else:
                  pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
          return pw
      except Exception as exc:
          log.exception('Failed to generate secure passsword')
          raise CommandExecutionError(six.text_type(exc)f secure_password(length=20, use_random=True):
      '''
      Generate a secure password.
      '''
      try:
          length = int(length)
          pw = ''
          while len(pw) < length:
              if HAS_RANDOM and use_random:
                  while True:
                      try:
                          char = salt.utils.stringutils.to_str(get_random_bytes(1))
                          break
                      except UnicodeDecodeError:
                          continue
                  pw += re.sub(
                      salt.utils.stringutils.to_str(r'\W'),
                      str(),  # future lint: disable=blacklisted-function
                      char
                  )
              else:
                  pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
          return pw
      except Exception as exc:
          log.exception('Failed to generate secure passsword')
          raise CommandExecutionError(six.text_type(exc))
docs: Generate a secure password.