def setup_class(self):
self.host = os.environ.get('KVIRT_HOST', '127.0.0.1')
self.user = os.environ.get('KVIRT_USER', 'root')
self.path = os.environ.get('KVIRT_PATH', '')
self.virttype = os.environ.get('KVIRT_TYPE', 'kvm')
self.libvirt_user = os.environ.get('KVIRT_LIBVIRT_USER', 'qemu')
k = Kvirt(self.host)
name = "test_%s" % ''.join(random.choice(string.lowercase) for i in range(5))
self.name = name
self.conn = k
python类lowercase()的实例源码
def add_disk(self, name, size, pool=None, thin=True, template=None, shareable=False, existing=None):
conn = self.conn
# diskformat = 'qcow2'
if size < 1:
print("Incorrect size.Leaving...")
return {'result': 'failure', 'reason': "Incorrect size"}
# if not thin:
# diskformat = 'raw'
try:
vm = conn.find_machine(name)
except:
common.pprint("VM %s not found" % name, color='red')
return {'result': 'failure', 'reason': "VM %s not found" % name}
disks = []
for index, dev in enumerate(string.lowercase[:10]):
try:
vm.get_medium('SATA', index, 0)
disks.append(0)
except:
continue
index = len(disks)
if existing is None:
storagename = "%s_%d" % (name, index)
diskpath = self.create_disk(name=storagename, size=size, pool=pool, thin=thin, template=template)
else:
disks = self.list_disks()
if existing in disks:
diskpath = disks[existing]['path']
else:
diskpath = existing
session = Session()
vm.lock_machine(session, library.LockType.write)
machine = session.machine
disk = conn.open_medium(diskpath, library.DeviceType.hard_disk, library.AccessMode.read_write, True)
machine.attach_device("SATA", index, 0, library.DeviceType.hard_disk, disk)
machine.save_settings()
session.unlock_machine()
return {'result': 'success'}
def letters(t):
letter_map = {}
for char in string.lowercase:
letter_map[char] = (t(char), string.capitalize(char))
return letter_map
def random_str(length=16):
""" Generates a random string, defaulting to 16 characters in length """
rand_str = lambda n: ''.join([random.choice(string.lowercase) for i in xrange(n)])
return rand_str(length)
def _is_snort_rule_invalid(rule):
'''Check if the snort rule given is invalid by trying to compile it.
rule -- Snort rule to test.
'''
filepath = '/tmp/tmp_' + ''.join(random.choice(string.lowercase) for i in range(8))
f = open(filepath, "w")
f.write(rule)
f.close()
if not rule.startswith('alert'):
return 'Snort rule does not start with "alert"'
if "threshold" in rule:
return 'threshold in snort rule is deprecated'
dp = dumbpig.RuleChecker()
dp.set_rule_file(filepath)
dp.test_rule_file()
os.remove(filepath)
result = json.dumps(dp.json_output()).encode('utf8').decode('string_escape')
if (result == '"{}"'):
return None
else:
return result
############################################
######## Attribute Check Functions #########
############################################
def __init__(self, grammar):
self.grammar = grammar
self.sax = pysax.SAXModel(
window=grammar.window_size,
stride=1,
nbins=grammar.paa_size,
alphabet=string.lowercase[:grammar.alphabet_size])
def randomword(length = 8):
return ''.join(random.choice(string.lowercase) for i in range(length))
def get_random_str(self, length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def mark_pod_as_deleted(pod_id):
p = db.session.query(Pod).get(pod_id)
if p is not None:
p.name += \
'__' + ''.join(random.sample(string.lowercase + string.digits, 8))
p.status = 'deleted'
db.session.commit()
def generate(length=8):
"""
Generates random lowercase+digits string
:param length: int -> default string length
:return: string -> random string
"""
rest = ''.join(random.sample(lowercase + digits, length - 1))
return random.choice(lowercase) + rest
def _autogen_subdomain(pod, base_domain):
"""
Generate Subdomain from Pod name or Pod Domain if Pod already has it
:param pod: Pod instance
:param base_domain: BaseDomain instance in which zone Subdomain should be
placed
:return: (pod_domain, sub_domain_part):
pod_domain -- if Pod Domain already exists for specified pod, else None
sub_domain_part -- autogenerated Subdomain part
"""
pod_domain = PodDomain.query.filter_by(domain_id=base_domain.id,
pod_id=pod.id).first()
if pod_domain:
return pod_domain, None
pod_name = domainize(pod.name)
if not pod_name:
pod_name = randstr(symbols=string.lowercase + string.digits,
length=8)
user = domainize(pod.owner.username)
sub_domain_part = '{0}-{1}'.format(user, pod_name)
sub_domain_part = _get_unique_domain_name(sub_domain_part, base_domain.id)
if sub_domain_part is None:
raise InternalAPIError('Failed to get unique pod domain name')
return None, sub_domain_part
def _get_unique_domain_name(basename, domain_id):
"""Returns unique domain name for given basename.
If basename does not exists in DB with specified domain_id, then it will
be returned as is.
Otherwise will be returned basename with random suffix
"""
pod_domain = PodDomain.query.filter_by(name=basename,
domain_id=domain_id).first()
if pod_domain is None:
return basename
res = None
# try to get unique random domain name. If it fails for tries limit,
# then something is going wrong, return None and it will be better to fail
# in calling code
tries_limit = 100
random_suffix_length = 6
for _ in xrange(tries_limit):
suffix = randstr(
symbols=string.lowercase + string.digits,
length=random_suffix_length)
new_name = '{0}{1}'.format(basename, suffix)
pod_domain = PodDomain.query.filter_by(
name=new_name, domain_id=domain_id).first()
if pod_domain is None:
res = new_name
break
return res
def delete(self):
self.name += '__' + ''.join(
random.sample(string.lowercase + string.digits, 8))
self.status = 'deleted'
# Such name to distinguish from non-db Pod's get_config() method
def _make_tag_list(n=26):
'''Returns a list of tag dicts, starting with 'aa, bb, ..., zz', then
'aaa, bbb, ..., zzz', etc. Tags must be at least 2 characters.'''
lc = string.lowercase
lc_len = len(lc)
return [{'name': lc[i % lc_len] * int(math.ceil(i / lc_len) + 2)}
for i in range(0, n)]
def random_password(self):
import string
import random
password = ''
specials = r'!#$*'
for i in range(0, 3):
password += random.choice(string.lowercase)
password += random.choice(string.uppercase)
password += random.choice(string.digits)
password += random.choice(specials)
return ''.join(random.sample(password, len(password)))
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
def get_random_key(size=10):
# Generates random sequence of chars
key = ""
for i in range(size):
key += random.choice(string.lowercase)
return key