python类digits()的实例源码

msgParser.py 文件源码 项目:Cortex-Analyzers 作者: CERT-BDF 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def save(self):
        # Use long filename as first preference
        filename = self.longFilename

        # Otherwise use the short filename
        if filename is None:
            filename = self.shortFilename
        # Otherwise just make something up!
        if filename is None:
            import random
            import string
            filename = 'UnknownFilename ' + \
                       ''.join(random.choice(string.ascii_uppercase + string.digits)
                               for _ in range(5)) + ".bin"
            #f = open("/tmp/" + filename, 'wb')
            # if self.data is None:
            #f.write(("Pas de PJ"))
            # f.close()
            # else:
            # f.write((self.data))
            # f.close()
            # return filename
Utils.py 文件源码 项目:newsreap 作者: caronc 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def hexdump(src, length=16, sep='.'):
    """
    Displays a hex output of the content it is passed.

    This was based on https://gist.github.com/7h3rAm/5603718 with some
    minor modifications
    """
    allowed = digits + ascii_letters + punctuation + ' '

    print_map = ''.join(((x if x in allowed else '.')
                        for x in map(chr, range(256))))
    lines = []

    for c in xrange(0, len(src), length):
        chars = src[c:c + length]
        hex = ' '.join(["%02x" % ord(x) for x in chars])
        if len(hex) > 24:
            hex = "%s %s" % (hex[:24], hex[24:])
        printable = ''.join(["%s" % (
            (ord(x) <= 127 and print_map[ord(x)]) or sep) for x in chars])
        lines.append("%08x:  %-*s  |%s|" % (c, length * 3, hex, printable))
    return '\n'.join(lines)
util.py 文件源码 项目:picoCTF 作者: picoCTF 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def sanitize_name(name):
    """
    Sanitize a given name such that it conforms to unix policy.

    Args:
        name: the name to sanitize.

    Returns:
        The sanitized form of name.
    """

    if len(name) == 0:
        raise Exception("Can not sanitize an empty field.")

    sanitized_name = re.sub(r"[^a-z0-9\+-]", "-", name.lower())

    if sanitized_name[0] in string.digits:
        sanitized_name = "p" + sanitized_name

    return sanitized_name

#I will never understand why the shutil functions act
#the way they do...
util.py 文件源码 项目:aiodownload 作者: jelloslinger 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def clean_filename(filename):
    """Return a sanitized filename (replace / strip out illegal characters)

    :param filename: string used for a filename
    :type filename: str

    :return: sanitized filename
    :rtype: str
    """

    return ''.join([
        c for c in unicodedata.normalize(
            'NFKD',
            ''.join([REPLACEMENT_CHAR.get(c, c) for c in filename])
        )
        if not unicodedata.combining(c) and c in '-_.() {0}{1}'.format(string.ascii_letters, string.digits)
    ])
forgot_password.py 文件源码 项目:PimuxBot 作者: Finn10111 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def index():
    if request.args.get('code'):
        unlock_code = request.args.get('code')
        # unlock, new password
        re = s.query(RecoveryEmail).filter(RecoveryEmail.password_code==unlock_code).one_or_none()
        if re:
            jid = re.jid
            re.password_code = None
            s.merge(re)
            s.commit()
            # set new password and send email
            email_address = re.email
            password = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(10))
            p = subprocess.Popen(['/usr/bin/prosodyctl', 'passwd', jid], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
            args = bytes("%s\n%s\n" % (password, password), encoding='utf8')
            p.communicate(args)
            sendMail(email_address, 'new password', password)
            content = render_template('success.html', message='password was sent')
        else:
            content = render_template('error.html', message='link invalid')
    else:
        content = render_template('index.html')
    return content
moviegross.py 文件源码 项目:plugin.video.exodus 作者: lastship 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def __get_f(self, s):
        i = 0
        t = ''
        l = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'
        while i < len(s):
            try:
                c1 = l.index(s[i])
                c2 = l.index(s[i + 1])
                t += chr(c1 << 2 & 255 | c2 >> 4)
                c3 = l.index(s[i + 2])
                t += chr(c2 << 4 & 255 | c3 >> 2)
                c4 = l.index(s[i + 3])
                t += chr(c3 << 6 & 255 | c4)
                i += 4
            except:
                break

        return t
test_memento.py 文件源码 项目:ipwb 作者: oduwsdl 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def startReplay(warcFilename):
    global p
    pathOfWARC = os.path.join(os.path.dirname(moduleLocation) +
                              '/samples/warcs/' + warcFilename)
    tempFilePath = '/tmp/' + ''.join(random.sample(
        string.ascii_uppercase + string.digits * 6, 6)) + '.cdxj'
    print('B2' + tempFilePath)
    p = Process(target=replay.start, args=[tempFilePath])
    p.start()
    sleep(5)

    cdxjList = indexer.indexFileAt(pathOfWARC, quiet=True)
    cdxj = '\n'.join(cdxjList)

    with open(tempFilePath, 'w') as f:
        f.write(cdxj)
aiosubdomainBrute.py 文件源码 项目:aiosubdomainBrute 作者: OOsec 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def test_wildcard_dns_record(self):
        global wildcard_dns_record
        ip_dic = {}
        genrandstr = lambda i: ''.join(random.choices(string.ascii_lowercase + string.digits, k=i))
        tasks = [asyncio.ensure_future(self.resolver.query(genrandstr(20) + '.' + self.domain, 'A')) for _ in range(6)]
        reqs = asyncio.gather(*tasks)
        result = self.loop.run_until_complete(reqs)
        for r in result:
            if ip_dic.get(r.ip[0]):
                ip_dic[r.ip[0]] += 1
                if ip_dic[r.ip[0]] > 3:
                    wildcard_dns_record = r.ip[0]
                    print(f'[*] Found wildcard dns record:{wildcard_dns_record}')
                    return
            else:
                ip_dic[r.ip[0]] = 1
toutiao.py 文件源码 项目:lichking 作者: melonrun 项目源码 文件源码 阅读 57 收藏 0 点赞 0 评论 0
def generate_article_url(self, response):
        as_id = ''.join(random.sample(string.ascii_letters + string.digits, 15))
        cp_id = ''.join(random.sample(string.ascii_letters + string.digits, 15))
        yield scrapy.Request(
            "http://www.toutiao.com/api/pc/feed/?category=news_tech&utm_source=toutiao&widen=1&max_behot_time=0" +
            "max_behot_time_tmp=" + str(int(time.time())) +
            "tadrequire=true&as=" + as_id + "&cp=" + cp_id + "&t=" + str(time.time()),
            callback=self.generate_article_url
        )
        article_list = json.loads(response.body)
        if article_list.get("message") != "success":
            return
        for article_detail in article_list.get('data'):
            # wenda gallery ad ?
            # news_tech and news_finance
            tag_url = article_detail.get('tag_url')
            if article_detail.get('article_genre') == 'article'\
                    and (tag_url == 'news_tech' or tag_url == 'news_finance'):
                yield scrapy.Request(
                    self.toutiao_url_pre + article_detail.get('source_url'),
                    callback=self.generate_article_content
                )
generator.py 文件源码 项目:AntiRansom 作者: YJesus 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def randompdf (path) :

    numpdf = (randint(1500,2000))

    for i in range(10):

        name = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"

        numwords = (randint(200,1000))

        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)

        words =[]

        for i in range(numwords):

            randomword  = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))])
            words.append(randomword)

        wordsinstring = ''.join(words)

        pdf.cell(200, 10, txt=wordsinstring, align="C")

        pdf.output(name)

        for i in range(numpdf):

            dupli = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"

            copyfile(name, dupli)
recipe-222109.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def str( number, radix ):
   """str( number, radix ) -- reverse function to int(str,radix) and long(str,radix)"""

   if not 2 <= radix <= 36:
      raise ValueError, "radix must be in 2..36"

   abc = string.digits + string.letters

   result = ''

   if number < 0:
      number = -number
      sign = '-'
   else:
      sign = ''

   while True:
      number, rdigit = divmod( number, radix )
      result = abc[rdigit] + result
      if number == 0:
         return sign + result

   # never here because number >= 0, radix > 0, we repeat (number /= radix)
recipe-578397.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def ex3(argv):

    password = ''

    for i in range(len(argv)):
        for j in range(int(argv[i])):
            if i == 0:
                password += string.uppercase[random.randint(0,len(string.uppercase)-1)]
            elif i == 1:
                password += string.lowercase[random.randint(0,len(string.lowercase)-1)]
            elif i == 2:
                password += string.digits[random.randint(0,len(string.digits)-1)]
            elif i == 3:
                password += string.punctuation[random.randint(0,len(string.punctuation)-1)]

    return ''.join(random.sample(password,len(password)))
recipe-498257.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def decode(chromosome):
    """Takes a chromosome (list) and returns an expression."""
    # this needs to be a mini state machine.
    # We expect a stream of number + operator pairs terminated with a number
    output = ""
    need_op = False
    for key in chromosome:
        gene = genes[key]
        if need_op:
            if gene in operators:
                output += gene
                need_op = False
            else:
                continue
        else:
            if gene in digits:
                output += gene
                need_op = True
            else:
                continue
    if not need_op:
        # we don't want an op hanging off the end
        output = output[:len(output)-1]
    return output
recipe-578161.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def transition_function(P):
    """
    The main principle on building the transition function is to think about
    the fact that every time we scan a new character from the input sequence
    the suffix should match with the prefix of the pattern. If that is not
    possible for every length of the suffix, the next state need to be the
    initial, otherwise the length of the suffix that matches properly will be
    exactly the next state.
    """
    alphabet = st.ascii_letters+st.punctuation+st.digits+st.whitespace
    m = len(P)
    trans = [{c:0 for c in alphabet} for i in range(m)]
    for s in range(m):
        for c in alphabet:
            k = min(m, s+1)
            while (P[:s]+c)[-k:] != P[:k]:
                k-=1

            trans[s][c]=k

    return trans
data_collector.py 文件源码 项目:privcount 作者: privcount 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def set_nickname(self, nickname):
        nickname = nickname.strip()

        # Do some basic validation of the nickname
        if len(nickname) > 19:
            logging.warning("Bad nickname length %d: %s", len(nickname), nickname)
            return False
        if not all(c in (string.ascii_letters + string.digits) for c in nickname):
            logging.warning("Bad nickname characters: %s", nickname)
            return False

        # Are we replacing an existing nickname?
        if self.nickname is not None:
            if self.nickname != nickname:
                logging.warning("Replacing nickname %s with %s", self.nickname, nickname)
            else:
                logging.debug("Duplicate nickname received %s", nickname)

        self.nickname = nickname

        return True
data_collector.py 文件源码 项目:privcount 作者: privcount 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def set_address(self, address):
        address = address.strip()

        # Do some basic validation of the address
        # Relays must all have IPv4 addresses, so just checking for IPv4 is ok
        if len(address) < 7 or len(address) > 15:
            logging.warning("Bad address length %d: %s", len(address), address)
            return False
        if not all(c in (string.digits + '.') for c in address):
            logging.warning("Bad address characters: %s", address)
            return False
        # We could check each component is between 0 and 255, but that's overkill

        # Are we replacing an existing address?
        if self.address is not None:
            if self.address != address:
                logging.warning("Replacing address %s with %s", self.address, address)
            else:
                logging.debug("Duplicate address received %s", address)

        self.address = address

        return True
challenge_micro.py 文件源码 项目:Round1 作者: general-ai-challenge 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def _get_mapping(self):
        numbers = string.digits
        mapping = {x: random.choice(numbers) + '.' for x in numbers}

        def feedback_provider(is_correct, question):
            key = self.get_original_question(question)
            do_prepend = random.choice([True, False])
            if do_prepend:
                prepend = random.choice(numbers)
            else:
                prepend = ''
            return prepend + mapping[key]
        self.task_gen_kwargs['provide_feedback'] = feedback_provider
        return mapping


# stems from 5.7
# TODO: description says "either 3 or 4 or 5 chars. Shown example for 3
# chars". So will it be always the same size of feedback for on task
# instance? Or can it be mixed? - this version is mixed
# same question for 5.13, 5.14, 5.15, 5.16, 5.17 and 5.18
google.py 文件源码 项目:dsub 作者: googlegenomics 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def convert_to_label_chars(s):
    """Turn the specified name and value into a valid Google label."""

    # We want the results to be user-friendly, not just functional.
    # So we can't base-64 encode it.
    #   * If upper-case: lower-case it
    #   * If the char is not a standard letter or digit. make it a dash
    accepted_characters = string.ascii_lowercase + string.digits + '-'

    def label_char_transform(char):
      if char in accepted_characters:
        return char
      if char in string.ascii_uppercase:
        return char.lower()
      return '-'

    return ''.join(label_char_transform(c) for c in s)
AuthMatrix.py 文件源码 项目:AuthMatrix 作者: SecurityInnovation 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def customReplace(toArray):
        ret = ArrayList()
        customPrefix = "#{AUTHMATRIX:"
        for to in toArray:
            toNew = to
            if customPrefix in to:
                if customPrefix+"RANDOM}" in to:
                    # This will produce a random 4 char numeric string
                    # Most common use case is for APIs that reject requests that are identical to a previous request
                    randomString = ''.join(random.choice(string.digits) for _ in range(4))
                    toNew = to.replace(customPrefix+"RANDOM}",randomString)
            ret.add(toNew)

        return ret




##
## DB Class that holds all configuration data
##
rebuild-ipod.py 文件源码 项目:atoolbox 作者: liweitianux 项目源码 文件源码 阅读 49 收藏 0 点赞 0 评论 0
def get_newname(path):
        def conv_char(ch):
            safe_char = string.ascii_letters + string.digits + "-_"
            if ch in safe_char:
                return ch
            return "_"
        #
        if path == ".":
            return path
        dirname, basename = os.path.split(path)
        base, ext = os.path.splitext(basename)
        newbase = "".join(map(conv_char, base))
        if basename == newbase+ext:
            return os.path.join(dirname, basename)
        if os.path.exists("%s/%s%s" % (dirname, newbase, ext)):
            i = 0
            while os.path.exists("%s/%s_%d%s" % (dirname, newbase, i, ext)):
                i += 1
            newbase += "_%d" % i
        newname = "%s/%s%s" % (dirname, newbase, ext)
        return newname
post_gen_project.py 文件源码 项目:cookiecutter-django-reactjs 作者: genomics-geek 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_random_string(length=50):
    """
    Returns a securely generated random string.
    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    punctuation = string.punctuation.replace('"', '').replace("'", '')
    punctuation = punctuation.replace('\\', '')
    if using_sysrandom:
        return ''.join(random.choice(
            string.digits + string.ascii_letters + punctuation
        ) for i in range(length))

    print(
        "Cookiecutter Django couldn't find a secure pseudo-random number generator on your system."
        " Please change change your SECRET_KEY variables in conf/settings/local.py and env.example"
        " manually."
    )
    return "CHANGEME!!"
shellshock.py 文件源码 项目:routersploit 作者: reverse-shell 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def check(self):
        number = int(random_text(6, alph=string.digits))
        solution = number - 1
        cmd = "echo $(({}-1))".format(number)

        marker = random_text(32)
        url = "{}:{}{}".format(self.target, self.port, self.path)

        for payload in self.payloads:
            injection = payload.replace("{{marker}}", marker).replace("{{cmd}}", cmd)

            headers = {
                self.header: injection,
            }

            response = http_request(method=self.method, url=url, headers=headers)
            if response is None:
                continue

            if str(solution) in response.text:
                self.valid = payload
                return True  # target is vulnerable

        return False  # target not vulnerable
util.py 文件源码 项目:picoCTF 作者: royragsdale 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def sanitize_name(name):
    """
    Sanitize a given name such that it conforms to unix policy.

    Args:
        name: the name to sanitize.

    Returns:
        The sanitized form of name.
    """

    if len(name) == 0:
        raise Exception("Can not sanitize an empty field.")

    sanitized_name = re.sub(r"[^a-z0-9\+-]", "-", name.lower())

    if sanitized_name[0] in string.digits:
        sanitized_name = "p" + sanitized_name

    return sanitized_name

#I will never understand why the shutil functions act
#the way they do...
irc.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def ping(self, user, text = None):
        """Measure round-trip delay to another IRC client.
        """
        if self._pings is None:
            self._pings = {}

        if text is None:
            chars = string.letters + string.digits + string.punctuation
            key = ''.join([random.choice(chars) for i in range(12)])
        else:
            key = str(text)
        self._pings[(user, key)] = time.time()
        self.ctcpMakeQuery(user, [('PING', key)])

        if len(self._pings) > self._MAX_PINGRING:
            # Remove some of the oldest entries.
            byValue = [(v, k) for (k, v) in self._pings.items()]
            byValue.sort()
            excess = self._MAX_PINGRING - len(self._pings)
            for i in xrange(excess):
                del self._pings[byValue[i][1]]
chathistory.py 文件源码 项目:znc-chathistory 作者: MuffinMedic 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def generate_batch(self, chathistory, target):
        if len(chathistory) > 0:
            # Generate a random alphanumeric BATCH ID
            batch_id = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(BATCH_ID_SIZE))
            # Place the BATCH start identifer to the beginning of the chathistory
            line = 'irc.znc.in BATCH +{} chathistory {}'.format(batch_id, target)
            self.send_chathistory(line)
            # Prepend the BATCH ID to each line from the chathistory
            for line in chathistory:
                #msg_id = uuid.uuid4()
                #line = '@batch={};draft/msgid={};{}'.format(batch_id, msg_id, line)
                line = '@batch={};{}'.format(batch_id, line)
                self.send_chathistory(line)
            # Place the BATCH end identifer to the beginning of the chathistory
            line = 'irc.znc.in BATCH -{}'.format(batch_id)
            self.send_chathistory(line)
        else:
            client = self.GetClient()
            self.send_error(client, 'ERR', 'NOT_FOUND')

    # Send the given line to the user
shellshock.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def check(self):
        number = int(random_text(6, alph=string.digits))
        solution = number - 1
        cmd = "echo $(({}-1))".format(number)

        marker = random_text(32)
        url = "{}:{}{}".format(self.target, self.port, self.path)

        for payload in self.payloads:
            injection = payload.replace("{{marker}}", marker).replace("{{cmd}}", cmd)

            headers = {
                self.header: injection,
            }

            response = http_request(method=self.method, url=url, headers=headers)
            if response is None:
                continue

            if str(solution) in response.text:
                self.valid = payload
                return True  # target is vulnerable

        return False  # target not vulnerable
utils.py 文件源码 项目:BrundleFuzz 作者: carlosgprado 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def random_alphabetical_string(self, maxlen = 1024, exact = False):
        """
        Filenames are usually rejected if they contain
        funky characters, blocking execution
        """
        if exact:
            string_len = maxlen

        else:
            string_len = random.randint(1, maxlen)

        alphabet = string.ascii_letters + string.digits

        s = ''.join(random.choice(alphabet) for _ in range(string_len))

        return s
host.py 文件源码 项目:charm-plumgrid-gateway 作者: openstack 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars))
encryption.py 文件源码 项目:margy 作者: opentower 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def ran(N):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

#given a string s, returns a list containing an encrypted string and a key
flora.py 文件源码 项目:flora 作者: Lamden 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def random_string(length):
    pool = string.ascii_letters + string.digits
    return ''.join(random.choice(pool) for i in range(length))


问题


面经


文章

微信
公众号

扫码关注公众号