Python string 模块,digits() 实例源码
我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用string.digits()。
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
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)
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...
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)
])
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 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)
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 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
)
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)
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)
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)))
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
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
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
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
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
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 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
##
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
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!!"
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
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...
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]]
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 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
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
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))
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
def random_string(length):
pool = string.ascii_letters + string.digits
return ''.join(random.choice(pool) for i in range(length))
def random_string(length):
pool = string.ascii_letters + string.digits
return ''.join(random.choice(pool) for i in range(length))
def random_string(length):
pool = string.ascii_letters + string.digits
return ''.join(random.choice(pool) for i 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 random_string(size=6, chars=string.ascii_uppercase + string.digits):
"""Get a random string of numbers and uppercase letters"""
return ''.join(random.choice(chars) for _ in range(size))
def create_rand_string(length):
return ''.join(random.choice(string.ascii_letters + string.digits + " ") for _ in range(length))
def _check_username(username):
return all([c in string.digits + string.ascii_lowercase for c in username.lower()])
def initialize(self):
# generate random 32 hexadecimal characters
self.enc_key = ''.join(self.random.choice(string.digits + 'abcdef') for _ in range(32))
self.welcome_message = "Welcome to Secure Encryption Service version 1.{}".format(self.random.randint(0,10))
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 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))
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))
def gen_client_ID(size=12, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
# Set `SMTP` to False in order to force the program to use HTTP and it's own C&C Web App.
def random_str(n=8):
allow = list(string.uppercase + string.digits)
r = []
for i in range(n):
r.append(random.choice(allow))
return ''.join(r)
# return ''.join(random.sample(allow, n))
# ??ssdb_008.py ???????????
def dump_flash_page (self, page_num):
'''
Print one page of flash contents.
'''
with self._start_communication_with_board():
address = 512 * page_num
print('Page number: {} ({:#08x})'.format(page_num, address))
flash = self.channel.read_range(address, 512)
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def dump_line (addr, bytes):
k = binascii.hexlify(bytes).decode('utf-8')
b = ' '.join(list(chunks(k, 2)))
if len(b) >= 26:
# add middle space
b = '{} {}'.format(b[0:24], b[24:])
printable = string.ascii_letters + string.digits + string.punctuation + ' '
t = ''.join([chr(i) if chr(i) in printable else '.' for i in bytes])
print('{:08x} {} |{}|'.format(addr, b, t))
for i,chunk in enumerate(chunks(flash, 16)):
dump_line(address+(i*16), chunk)
############################################################################
## Internal Helper Functions for Communicating with Boards
############################################################################
def expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif not 'HOMEPATH' in os.environ:
return path
else:
try:
drive = os.environ['HOMEDRIVE']
except KeyError:
drive = ''
userhome = join(drive, os.environ['HOMEPATH'])
if i != 1: #~user
userhome = join(dirname(userhome), path[1:i])
return userhome + path[i:]
# Expand paths containing shell variable substitutions.
# The following rules apply:
# - no expansion within single quotes
# - '$$' is translated into '$'
# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
# - ${varname} is accepted.
# - $varname is accepted.
# - %varname% is accepted.
# - varnames can be made out of letters, digits and the characters '_-'
# (though is not verified in the ${varname} and %varname% cases)
# XXX With COMMAND.COM you can use any characters in a variable name,
# XXX except '^|<>='.
def _random_file_name(self):
randfile = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(12)])
if self.os_type == 1:
workdir = 'c:\\windows\\temp'
else:
workdir = '/tmp'
return self.path_join(workdir, 'cblr.%s.tmp' % (randfile,))