def __init__(self, var):
if var[0] not in (string.letters + "_"):
raise InvalidVarException("variable names must start with a "
"letter or underscore")
self.var = var
python类letters()的实例源码
def __setattr__(self, name, value):
if name == ('attr_prefix', 'text_key', 'cdata_prefix') and value is not None:
if any(c in string.letters or c == '_' for c in value):
raise XMLSchemaValueError(
'%r cannot include letters or underscores: %r' % (name, value))
super(NamespaceMapper, self).__setattr__(name, value)
def __init__(self, *args, **kwargs):
self.procedures = RemoteProcedures()
self.prefixes = Prefixes()
self.session_id = ''.join(
[random.choice(string.digits + string.letters)
for i in xrange(16)])
super(WampProtocol, self).__init__(*args, **kwargs)
def name(self, name):
if name:
chars = []
for c in name:
chars.append(c)
if c not in string.digits + string.letters + "_-.":
raise ValueError("Invalid job name: '{0}'. "
"Illegal character {1} {2}".format(name, c,
chars))
self._name = name
def random_string(length):
"""
Return a pseudo-random string of specified length.
"""
valid_chars = string_ascii_letters + string_digits
return ''.join(random.choice(valid_chars) for i in range(length))
def thunk(input_str):
ok_chars = string.letters + string.digits + "_"
output_str = input_str
for character in output_str:
if not character in ok_chars:
output_str = output_str.replace(character,"_")
if output_str[0] in string.digits:
output_str = "_" + output_str
return output_str
def generateSalt(self,size=SALT_SIZE):
return ''.join(random.SystemRandom().choice(string.letters + string.digits) for _ in range(size))
def random_string():
return random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] )
def get_img(self):
try:
imgur = "None"
download_img = True
print((colored('[+] Downloading image from Cloud Service...', 'white')))
while download_img:
# Remove not valid img downloaded
if (os.path.isfile(imgur)):
os.remove(imgur)
imgur = ''.join(random.sample(string.letters+string.digits, 5)) + '.jpg'
img = urllib2.urlopen("http://i.imgur.com/" + imgur).read()
if len(img) != 503: # 'image not found' is 503 bytes
with open(os.path.join('./', imgur), "wb") as f:
f.write(img)
f.close()
with Image.open(imgur) as im:
width, height = im.size
# Enough big to insert data
if (width > 400 and height > 400):
download_img = False
return imgur
except:
print((colored("[-] Get image error", "yellow")))
if (os.path.isfile(imgur)):
os.remove(imgur)
def get_img(self):
try:
imgur = "None"
download_img = True
print((colored('[+] Downloading image from Cloud Service...', 'white')))
while download_img:
# Remove not valid image downloaded
if (os.path.isfile(imgur)):
os.remove(imgur)
imgur = ''.join(random.sample(string.letters+string.digits, 5)) + '.jpg'
img = urllib2.urlopen("http://i.imgur.com/" + imgur).read()
if len(img) != 503: # 'image not found' is 503 bytes
with open(os.path.join('./', imgur), "wb") as f:
f.write(img)
f.close()
with Image.open(imgur) as im:
width, height = im.size
# Big enough to insert data
if (width > 400 and height > 400):
download_img = False
return imgur
except:
print 'Get image error'
if (os.path.isfile(imgur)):
os.remove(imgur)
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None):
'''This adds the same transition for a list of input symbols.
You can pass a list or a string. Note that it is handy to use
string.digits, string.whitespace, string.letters, etc. to add
transitions that match character classes.
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state will be unchanged. '''
if next_state is None:
next_state = state
for input_symbol in list_input_symbols:
self.add_transition (input_symbol, state, action, next_state)
def save_password(password, port):
"""
Used by main() to save the password in the parameters_port.py file.
"""
password_file = abspath('parameters_%i.py' % port)
if password == '<random>':
# make up a new password
chars = string.letters + string.digits
password = ''.join([random.choice(chars) for _ in range(8)])
cpassword = CRYPT()(password)[0]
print('******************* IMPORTANT!!! ************************')
print('your admin password is "%s"' % password)
print('*********************************************************')
elif password == '<recycle>':
# reuse the current password if any
if exists(password_file):
return
else:
password = ''
elif password.startswith('<pam_user:'):
# use the pam password for specified user
cpassword = password[1:-1]
else:
# use provided password
cpassword = CRYPT()(password)[0]
fp = open(password_file, 'w')
if password:
fp.write('password="%s"\n' % cpassword)
else:
fp.write('password=None\n')
fp.close()
def __init__(self, listenAddress = '0.0.0.0', listenPort=445, configFile=''):
if configFile != '':
self.__server = SMBSERVER((listenAddress,listenPort))
self.__server.processConfigFile(configFile)
self.__smbConfig = None
else:
# Here we write a mini config for the server
self.__smbConfig = ConfigParser.ConfigParser()
self.__smbConfig.add_section('global')
self.__smbConfig.set('global','server_name',''.join([random.choice(string.letters) for _ in range(8)]))
self.__smbConfig.set('global','server_os',''.join([random.choice(string.letters) for _ in range(8)])
)
self.__smbConfig.set('global','server_domain',''.join([random.choice(string.letters) for _ in range(8)])
)
self.__smbConfig.set('global','log_file','None')
self.__smbConfig.set('global','rpc_apis','yes')
self.__smbConfig.set('global','credentials_file','')
self.__smbConfig.set('global', 'challenge', "A"*8)
# IPC always needed
self.__smbConfig.add_section('IPC$')
self.__smbConfig.set('IPC$','comment','')
self.__smbConfig.set('IPC$','read only','yes')
self.__smbConfig.set('IPC$','share type','3')
self.__smbConfig.set('IPC$','path','')
self.__server = SMBSERVER((listenAddress,listenPort), config_parser = self.__smbConfig)
self.__server.processConfigFile()
# Now we have to register the MS-SRVS server. This specially important for
# Windows 7+ and Mavericks clients since they WONT (specially OSX)
# ask for shares using MS-RAP.
self.__srvsServer = SRVSServer()
self.__srvsServer.daemon = True
self.__wkstServer = WKSTServer()
self.__wkstServer.daemon = True
self.__server.registerNamedPipe('srvsvc',('127.0.0.1',self.__srvsServer.getListenPort()))
self.__server.registerNamedPipe('wkssvc',('127.0.0.1',self.__wkstServer.getListenPort()))
def __init__(self, SMBObject, exeFile):
self._rpctransport = 0
self.__service_name = ''.join([random.choice(string.letters) for i in range(4)])
self.__binary_service_name = ''.join([random.choice(string.letters) for i in range(8)]) + '.exe'
self.__exeFile = exeFile
# We might receive two different types of objects, always end up
# with a SMBConnection one
if isinstance(SMBObject, smb.SMB) or isinstance(SMBObject, smb3.SMB3):
self.connection = SMBConnection(existingConnection = SMBObject)
else:
self.connection = SMBObject
self.share = ''
def __retrieveHive(self, hiveName):
tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp'
ans = rrp.hOpenLocalMachine(self.__rrp)
regHandle = ans['phKey']
try:
ans = rrp.hBaseRegCreateKey(self.__rrp, regHandle, hiveName)
except:
raise Exception("Can't open %s hive" % hiveName)
keyHandle = ans['phkResult']
rrp.hBaseRegSaveKey(self.__rrp, keyHandle, tmpFileName)
rrp.hBaseRegCloseKey(self.__rrp, keyHandle)
rrp.hBaseRegCloseKey(self.__rrp, regHandle)
# Now let's open the remote file, so it can be read later
remoteFileName = RemoteFile(self.__smbConnection, 'SYSTEM32\\'+tmpFileName)
return remoteFileName
def makeSafeFilename(inputFilename):
try:
safechars = string.letters + string.digits + "-_."
return filter(lambda c: c in safechars, inputFilename)
except:
return ""
###################################################################################################
# Check if resource exist
###################################################################################################
def string(size):
return ''.join([random.choice(string.letters) for i in xrange(size)])
def alphanumeric(size):
return ''.join([random.choice(string.letters + string.digits)
for i in xrange(size)])
def printable(data):
printable = string.digits + string.letters + string.punctuation + ' '
return ''.join([c if c in printable else '.' for c in data])
def randstr_n(n, chars=string.letters + string.digits):
return ''.join(
random.choice(chars) for _ in range(n)
)
# Generate static random integers
# to help filling actions['render']