Python string.digits() Examples

The following are 30 code examples for showing how to use string.digits(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: ssh.py    License: Apache License 2.0 7 votes vote down vote up
def scp(args):
    """
    Transfer files to or from EC2 instance.
    """
    scp_opts, host_opts = extract_passthrough_opts(args, "scp"), []
    user_or_hostname_chars = string.ascii_letters + string.digits
    ssm_init_complete = False
    for i, arg in enumerate(args.scp_args):
        if arg[0] in user_or_hostname_chars and ":" in arg:
            hostname, colon, path = arg.partition(":")
            username, at, hostname = hostname.rpartition("@")
            if args.use_ssm and not ssm_init_complete:
                scp_opts += init_ssm(get_instance(hostname).id)
                ssm_init_complete = True
            host_opts, hostname = prepare_ssh_host_opts(username=username, hostname=hostname,
                                                        bless_config_filename=args.bless_config,
                                                        use_kms_auth=args.use_kms_auth, use_ssm=args.use_ssm)
            args.scp_args[i] = hostname + colon + path
    os.execvp("scp", ["scp"] + scp_opts + host_opts + args.scp_args) 
Example 2
Project: XFLTReaT   Author: earthquake   File: DNS.py    License: MIT License 7 votes vote down vote up
def cmh_autotune(self, module, message, additional_data, cm):
		message = message[len(self.CONTROL_AUTOTUNE)+2:]
		# get tune type, requested record type, length and encoding for crafting the answer
		(query_type, RRtype, length, encode_class) = struct.unpack("<BHHH", message[0:7])
		if self.DNS_proto.get_RR_type(RRtype)[0] == None:
			return True
		
		# extra parameters added to be able to response in the proper way
		additional_data = additional_data + (True, self.download_encoding_list[encode_class], self.DNS_proto.get_RR_type(RRtype)[0])		
		if (query_type == 0) or (query_type == 3):
			# record && downstream length discovery
			message = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
		if query_type == 1:
			# A record name length discovery
			message = struct.pack("<i", binascii.crc32(message[7:]))
		if query_type == 2:
			# checking download encoding, echoing back request payload
			message = message[7:]

		module.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_AUTOTUNE_CLIENT+message, additional_data)
		return True

	# tune control message handler
	# client sets the record type and encodings by calling this
	# server side 
Example 3
Project: vault   Author: gabfl   File: Encryption.py    License: MIT License 7 votes vote down vote up
def gen_salt(self, set_=True):
        """
            Generate a random salt
        """

        min_char = 8
        max_char = 12
        allchar = string.ascii_letters + string.punctuation + string.digits
        salt = "".join(choice(allchar)
                       for x in range(randint(min_char, max_char))).encode()

        # Set the salt in the same instance if required
        if set_:
            self.set_salt(salt)

        return salt 
Example 4
Project: stream   Author: gynvael   File: casm.py    License: MIT License 7 votes vote down vote up
def s_cname(s, t):
  CNAME0 = string.ascii_letters + "_.!:"
  CNAME1 = string.ascii_letters + string.digits + "_."

  token = ""
  if s.peek() not in CNAME0:
    return False

  token = s.get()

  try:
    while s.peek() in CNAME1:
      token += s.get()
  except StreamException:
    pass

  t.append((TokenTypes.IDENTIFIER, token))  # TODO: maybe add more info on type

  return True 
Example 5
Project: stream   Author: gynvael   File: casm.py    License: MIT License 7 votes vote down vote up
def s_ctype(s, t):
  CTYPE0 = string.ascii_letters + "_.!:"
  CTYPE1 = string.ascii_letters + string.digits + "_."

  token = ""
  if s.peek() not in CTYPE0:
    return False

  token = s.get()

  try:
    while s.peek() in CTYPE1:
      token += s.get()
  except StreamException:
    pass

  t.append(token)  # TODO: maybe add more info on type

  return True 
Example 6
Project: tomlkit   Author: sdispater   File: items.py    License: MIT License 7 votes vote down vote up
def __init__(
        self, k, t=None, sep=None, dotted=False
    ):  # type: (str, Optional[KeyType], Optional[str], bool) -> None
        if t is None:
            if any(
                [c not in string.ascii_letters + string.digits + "-" + "_" for c in k]
            ):
                t = KeyType.Basic
            else:
                t = KeyType.Bare

        self.t = t
        if sep is None:
            sep = " = "

        self.sep = sep
        self.key = k
        self._dotted = dotted 
Example 7
Project: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 8
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 9
Project: hydrus   Author: HTTP-APIs   File: test_cli.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 10
Project: friendly-telegram   Author: friendly-telegram   File: configurator.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def api_config():
    """Request API config from user and set"""
    code, hash_value = DIALOG.inputbox("Enter your API Hash")
    if code == DIALOG.OK:
        if len(hash_value) != 32 or any(it not in string.hexdigits for it in hash_value):
            DIALOG.msgbox("Invalid hash")
            return
        string1 = "HASH = \"" + hash_value + "\""
        code, id_value = DIALOG.inputbox("Enter your API ID")
        if not id_value or any(it not in string.digits for it in id_value):
            DIALOG.msgbox("Invalid ID")
            return
        string2 = "ID = \"" + id_value + "\""
        with open(os.path.join(utils.get_base_dir(), "api_token.py"), "w") as file:
            file.write(string1 + "\n" + string2 + "\n")
        DIALOG.msgbox("API Token and ID set.") 
Example 11
Project: aws-batch-example   Author: dejonghe   File: lambda_function.py    License: MIT License 6 votes vote down vote up
def lambda_handler(event,context):
    # Grab data from environment
    jobqueue = os.environ['JobQueue']
    jobdef = os.environ['JobDefinition']

    # Create unique name for the job (this does not need to be unique)
    job1Name = 'job1' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))

    # Set up a batch client 
    session = boto3.session.Session()
    client = session.client('batch')

    # Submit the job
    job1 = client.submit_job(
        jobName=job1Name,
        jobQueue=jobqueue,
        jobDefinition=jobdef
    )
    print("Started Job: {}".format(job1['jobName'])) 
Example 12
Project: ICDAR-2019-SROIE   Author: zzzDavid   File: my_utils.py    License: MIT License 6 votes vote down vote up
def random_string(n):
    if n == 0:
        return ""

    x = random.random()
    if x > 0.5:
        pad = " " * n
    elif x > 0.3:
        pad = "".join(random.choices(digits + " \t\n", k=n))
    elif x > 0.2:
        pad = "".join(random.choices(ascii_uppercase + " \t\n", k=n))
    elif x > 0.1:
        pad = "".join(random.choices(ascii_uppercase + digits + " \t\n", k=n))
    else:
        pad = "".join(
            random.choices(ascii_uppercase + digits + punctuation + " \t\n", k=n)
        )

    return pad 
Example 13
Project: conan-center-index   Author: conan-io   File: conanfile.py    License: MIT License 6 votes vote down vote up
def _library_name(self):
        libname = "jemalloc"
        if self.settings.compiler == "Visual Studio":
            if self.options.shared:
                if self.settings.build_type == "Debug":
                    libname += "d"
            else:
                toolset = msvs_toolset(self.settings)
                toolset_number = "".join(c for c in toolset if c in string.digits)
                libname += "-vc{}-{}".format(toolset_number, self._msvc_build_type)
        else:
            if self.settings.os == "Windows":
                if not self.options.shared:
                    libname += "_s"
            else:
                if not self.options.shared and self.options.fPIC:
                    libname += "_pic"
        return libname 
Example 14
Project: instavpn   Author: sockeye44   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def setup_passwords():
    try:
        char_set = string.ascii_lowercase + string.ascii_uppercase + string.digits
        f = open('/etc/ppp/chap-secrets', 'w')
        pw1 = gen_random_text(12)
        pw2 = gen_random_text(12)
        f.write("username1 l2tpd {} *\n".format(pw1))
        f.write("username2 l2tpd {} *".format(pw2))
        f.close()
        f = open('/etc/ipsec.secrets', 'w')
        f.write('1.2.3.4 %any: PSK "{}"'.format(gen_random_text(16)))
        f.close()
    except:
        logger.exception("Exception creating passwords:")
        return False

    return True 
Example 15
Project: maubot   Author: maubot   File: client_auth.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def login(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, _, username, password, _ = info
    device_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    try:
        return web.json_response(await api.request(Method.POST, Path.login, content={
            "type": "m.login.password",
            "identifier": {
                "type": "m.id.user",
                "user": username,
            },
            "password": password,
            "device_id": f"maubot_{device_id}",
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
        }, status=e.http_status) 
Example 16
Project: wanggeService   Author: pchaos   File: base.py    License: MIT License 6 votes vote down vote up
def getRandomStr(types='letter', length=8):
        """ 随机产生length长度的字符串

        :param types: 随机字符串的类型
        types in ['letter', 'ascii'] 返回包含字母的字符串
        types in ['digit', 'num']: 返回包含数字的字符串
        其他:返回混合字母和数字的字符串

        :param length: 返回字符串的长度
        :return: 长度为length,类型为types的字符串

        todo string.punctuation

        """
        import random
        import string
        if types in ['letter', 'ascii']:
            return ''.join(random.sample(string.ascii_letters, length))
        if types in ['digit', 'num']:
            return ''.join(random.sample(string.digits, length))
        else:
            return ''.join(random.sample(string.ascii_letters + string.digits, length)) 
Example 17
Project: mlbv   Author: kmac   File: mlbsession.py    License: GNU General Public License v3.0 5 votes vote down vote up
def gen_random_string(n):
    return ''.join(
        random.choice(
            string.ascii_uppercase + string.digits
        ) for _ in range(n)
    ) 
Example 18
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    License: MIT License 5 votes vote down vote up
def generatebase64(seed: int) -> str:
    random.seed(seed)
    letters = string.ascii_letters + string.digits + "+/="
    return "".join(random.choices(letters, k=20)) 
Example 19
Project: backtrader-cn   Author: pandalibin   File: sina.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_random_string(length=8, digits_only=True):
    """
    获取随机字符串长度
    :param length:
    :param digits_only:
    :return:
    """
    random_str = ""
    random_list = string.digits if digits_only else string.ascii_letters + string.digits
    for i in range(length):
        random_str += random.choice(random_list)
    return random_str 
Example 20
Project: aegea   Author: kislyuk   File: iam.py    License: Apache License 2.0 5 votes vote down vote up
def generate_password(length=16):
    while True:
        password = [random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)]
        password.insert(8, "-")
        if not any(c in string.ascii_uppercase for c in password):
            continue
        if not any(c in string.ascii_lowercase for c in password):
            continue
        if not any(c in string.digits for c in password):
            continue
        return ''.join(password) 
Example 21
Project: BASS   Author: Cisco-Talos   File: kamino.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _translate_db(db, name = None):
    return {
        "name": name if name is not None else ("random_%s" % "".join(random.choice(string.letters + string.digits) for _ in range(32))),
        "architecture": {
            "type": db.architecture_name,
            "size": {32: "b32", 64: "b64"}[db.architecture_bits],
            "endian": {"little": "le", "big": "be"}[db.architecture_endianness],
        },
        "functions": [{
            "name": func.name,
            "id": func.entry_point,
            "call": func.calls,
            "api": func.apis,
            "sea": func.entry_point,
            "see": max(chunk.end for chunk in func.chunks),
            "blocks": [{
                "id": bb.id,
                "sea": bb.start + (1 if bb.thumb else 0),
                "eea": bb.end,
                "name": bb.name,
                "bytes": "".join("%02x" % ord(x) for x in bb.bytes),
                "dat": dict((hd.address, "".join("%02x" % ord(y) for y in db.get_bytes(hd.data_refs[0], hd.data_refs[0] + 8))) \
                        for hd in bb.code_heads if len(hd.data_refs) >= 1 and db.get_bytes(hd.data_refs[0], hd.data_refs[0] + 8) is not None),
                "src": [("0x%X" % hd.address, hd.disassembly.split()[0]) + tuple(op["opnd"] for op in hd.data["operands"]) \
                        for hd in bb.code_heads if hd.mnemonic != ""],
                "call": [succ.id for succ in bb.successors]} for bb in func.basic_blocks],
        } for func in db.functions],
    } 
Example 22
Project: wechatpy   Author: wechatpy   File: utils.py    License: MIT License 5 votes vote down vote up
def random_string(length=16):
    rule = string.ascii_letters + string.digits
    rand_list = random.sample(rule, length)
    return "".join(rand_list) 
Example 23
Project: friendly-telegram   Author: friendly-telegram   File: initial_setup.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def set_tg_api(self, request):
        if self.client_data and await self.check_user(request) is None:
            return web.Response(status=302, headers={"Location": "/"})  # They gotta sign in.
        text = await request.text()
        if len(text) < 36:
            return web.Response(status=400)
        api_id = text[32:]
        api_hash = text[:32]
        if any(c not in string.hexdigits for c in api_hash) or any(c not in string.digits for c in api_id):
            return web.Response(status=400)
        with open(os.path.join(utils.get_base_dir(), "api_token.py"), "w") as f:
            f.write("HASH = \"" + api_hash + "\"\nID = \"" + api_id + "\"\n")
        self.api_token = collections.namedtuple("api_token", ("ID", "HASH"))(api_id, api_hash)
        self.api_set.set()
        return web.Response() 
Example 24
Project: friendly-telegram   Author: friendly-telegram   File: initial_setup.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def tg_code(self, request):
        if self.client_data and await self.check_user(request) is None:
            return web.Response(status=302, headers={"Location": "/"})  # They gotta sign in.
        text = await request.text()
        if len(text) < 6:
            return web.Response(status=400)
        split = text.split("\n", 2)
        if len(split) not in (2, 3):
            return web.Response(status=400)
        code = split[0]
        phone = telethon.utils.parse_phone(split[1])
        password = split[2]
        if (len(code) != 5 and not password) or any(c not in string.digits for c in code) or not phone:
            return web.Response(status=400)
        client = self.sign_in_clients[phone]
        if not password:
            try:
                user = await client.sign_in(phone, code=code)
            except telethon.errors.SessionPasswordNeededError:
                return web.Response(status=401)  # Requires 2FA login
            except telethon.errors.PhoneCodeExpiredError:
                return web.Response(status=404)
            except telethon.errors.PhoneCodeInvalidError:
                return web.Response(status=403)
            except telethon.errors.FloodWaitError:
                return web.Response(status=421)
        else:
            try:
                user = await client.sign_in(phone, password=password)
            except telethon.errors.PasswordHashInvalidError:
                return web.Response(status=403)  # Invalid 2FA password
            except telethon.errors.FloodWaitError:
                return web.Response(status=421)
        del self.sign_in_clients[phone]
        client.phone = "+" + user.phone
        self.clients.append(client)
        secret = secrets.token_urlsafe()
        self._pending_secret_to_uid[secret] = user.id
        return web.Response(text=secret) 
Example 25
Project: jsonrpcclient   Author: bcb   File: id_generators.py    License: MIT License 5 votes vote down vote up
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]:
    """
    A random string.

    Not unique, but has around 1 in a million chance of collision (with the default 8
    character length). e.g. 'fubui5e6'

    Args:
        length: Length of the random string.
        chars: The characters to randomly choose from.
    """
    while True:
        yield "".join([choice(chars) for _ in range(length)]) 
Example 26
Project: pythonjobs.ie   Author: kimeraapp   File: services.py    License: GNU General Public License v2.0 5 votes vote down vote up
def generate_token(length=60):
    chars = string.ascii_uppercase + string.digits
    return ''.join(random.choice(chars) for _ in range(length)) 
Example 27
Project: ToonRooter   Author: martenjacobs   File: rooter.py    License: MIT License 5 votes vote down vote up
def patch_toon(self):
        (port, clean_up, reboot) = (
            self._port, self._cleanup_payload, self._reboot_after)
        log.info("Patching Toon")
        log.debug(port.read_until("/ # "))
        password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
        port.write("sh payload/patch_toon.sh \"{}\"\n".format(password))
        try:
            while True:
                line = read_until(port, ["/ # ", "\n"])
                if line == "/ # ":
                    break
                if line.startswith(">>>"):
                    log.info(line.strip())
                else:
                    log.debug(line.strip())
        except:
            log.exception("Script failed")
            sleep(5)
        if clean_up:
            log.info("Cleaning up")
            port.write("rm -r payload\n")
            log.debug(port.read_until("/ # "))
        if reboot:
            log.info("Rebooting")
            port.write("/etc/init.d/reboot\n") 
Example 28
def test_recordio_pack_label():
    frec = tempfile.mktemp()
    N = 255

    for i in range(1, N):
        for j in range(N):
            content = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(j))
            content = content.encode('utf-8')
            label = np.random.uniform(size=i).astype(np.float32)
            header = (0, label, 0, 0)
            s = mx.recordio.pack(header, content)
            rheader, rcontent = mx.recordio.unpack(s)
            assert (label == rheader.label).all()
            assert content == rcontent 
Example 29
Project: comport   Author: codeforamerica   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def random_string(N):
    return ''.join(choice(string.ascii_uppercase + string.digits + '     ') for _ in range(N)) 
Example 30
Project: fishroom   Author: tuna   File: api_client.py    License: GNU General Public License v3.0 5 votes vote down vote up
def token_id_gen(N):
        return ''.join(
            random.choice(string.digits)
            for _ in range(N)
        )