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:
python类ascii_lowercase()的实例源码
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))