Python string.letters() Examples

The following are 30 code examples for showing how to use string.letters(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: sparta   Author: SECFORCE   File: ms08-067_check.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __forgePacket(self):
        '''
        Forge the malicious NetprPathCompare packet

        Reference: http://msdn.microsoft.com/en-us/library/cc247259.aspx

        long NetprPathCompare(
          [in, string, unique] SRVSVC_HANDLE ServerName,
          [in, string] WCHAR* PathName1,
          [in, string] WCHAR* PathName2,
          [in] DWORD PathType,
          [in] DWORD Flags
        );
        '''

        self.__path = ''.join([choice(letters) for _ in xrange(0, 3)])

        self.__request  = ndr_unique(pointer_value=0x00020000, data=ndr_wstring(data='')).serialize()
        self.__request += ndr_wstring(data='\\%s\\..\\%s' % ('A'*5, self.__path)).serialize()
        self.__request += ndr_wstring(data='\\%s' % self.__path).serialize()
        self.__request += ndr_long(data=1).serialize()
        self.__request += ndr_long(data=0).serialize() 
Example 2
Project: CVE-2017-7494   Author: joxeankoret   File: secretsdump.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __executeRemote(self, data):
        self.__tmpServiceName = ''.join([random.choice(string.letters) for _ in range(8)]).encode('utf-16le')
        command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' > ' + self.__batchFile + ' & ' + \
                  self.__shell + self.__batchFile
        command += ' & ' + 'del ' + self.__batchFile

        self.__serviceDeleted = False
        resp = scmr.hRCreateServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName, self.__tmpServiceName,
                                     lpBinaryPathName=command)
        service = resp['lpServiceHandle']
        try:
           scmr.hRStartServiceW(self.__scmr, service)
        except:
           pass
        scmr.hRDeleteService(self.__scmr, service)
        self.__serviceDeleted = True
        scmr.hRCloseServiceHandle(self.__scmr, service) 
Example 3
Project: Webshell-Sniper   Author: WangYihang   File: WebShell.py    License: GNU General Public License v3.0 6 votes vote down vote up
def auto_inject_phpfile(self, filename, webshell_content):
        Log.info("Auto injecting : [%s] => [%s]" % (filename, repr(webshell_content)))
        Log.info("Code : [%s]" % (repr(webshell_content)))
        Log.info("Length : [%d]" % (len(webshell_content)))
        Log.info("Getting writable dirs...")
        writable_dirs = self.get_writable_directory()
        urls = []
        if len(writable_dirs) == 0:
            Log.error("No writable dirs...")
            return False
        else:
            for writable_dir in writable_dirs:
                writable_dir += "/"
                filename = ".%s.php" % (random_string(16, string.letters + string.digits))
                Log.info("Writing [%s] into : [%s]" % (repr(webshell_content), writable_dir))
                php_code = "file_put_contents('%s',base64_decode('%s'));" % ("%s/%s" % (writable_dir, filename), webshell_content.encode("base64").replace("\n",""))
                self.php_code_exec(php_code)
                base_url = "%s%s" % ("".join(["%s/" % (i) for i in self.url.split("/")[0:3]]), writable_dir.replace("%s" % (self.webroot), ""))
                webshell_url = ("%s%s" % (base_url, filename)).replace("//", "/").replace("https:/", "https://").replace("http:/", "http://")
                with open("Webshell.txt", "a+") as f:
                    log_content = "%s => %s\n" % (webshell_url, repr(webshell_content))
                    f.write(log_content)
                urls.append(webshell_url)
        return urls 
Example 4
Project: avocado-vt   Author: avocado-framework   File: cmd_runner.py    License: GNU General Public License v2.0 6 votes vote down vote up
def run(self, m_cmd, t_cmd, r_path, timeout):
        """
        Main thread for testing, will do clean up afterwards
        """
        pid_file = "/tmp/pid_file_%s" % "".join(random.sample(string.letters,
                                                              4))
        monitor = threading.Thread(target=self.monitor_thread, args=(m_cmd,
                                                                     pid_file, r_path))
        test_runner = threading.Thread(target=self.test_thread, args=(m_cmd,
                                                                      t_cmd, pid_file))

        monitor.start()
        test_runner.start()
        monitor.join(timeout)
        if self.kill_thread_flag:
            self.thread_kill(m_cmd, pid_file)
            self.thread_kill(t_cmd, pid_file)
            self.kill_thread_flag = False 
Example 5
Project: daf-recipes   Author: italia   File: validators.py    License: GNU General Public License v3.0 6 votes vote down vote up
def url_validator(key, data, errors, context):
    ''' Checks that the provided value (if it is present) is a valid URL '''
    import urlparse
    import string

    model = context['model']
    session = context['session']

    url = data.get(key, None)
    if not url:
        return

    pieces = urlparse.urlparse(url)
    if all([pieces.scheme, pieces.netloc]) and \
       set(pieces.netloc) <= set(string.letters + string.digits + '-.') and \
       pieces.scheme in ['http', 'https']:
       return

    errors[key].append(_('Please provide a valid URL')) 
Example 6
Project: featherduster   Author: nccgroup   File: helpers.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_base64_encoded(sample):
   '''
   Check if a sample is likely base64-encoded
   
   sample - (string) The sample to evaluate
   '''
   base64chars = string.letters + string.digits + string.whitespace
   base64chars += '/+='
   # Turns out a lot of crazy things will b64-decode happily with
   # sample.decode('base64'). This is the fix.
   if any([char not in base64chars for char in sample]):
      return False
   try:
      sample.decode('base64')
      return True
   except:
      return False 
Example 7
Project: Safejumper-for-Desktop   Author: proxysh   File: irc.py    License: GNU General Public License v2.0 6 votes vote down vote up
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]] 
Example 8
Project: Fluid-Designer   Author: Microvellum   File: para.py    License: GNU General Public License v3.0 6 votes vote down vote up
def readColor(text):
    """Read color names or tuples, RGB or CMYK, and return a Color object."""
    if not text:
        return None
    from reportlab.lib import colors
    from string import letters
    if text[0] in letters:
        return colors.__dict__[text]
    tup = lengthSequence(text)

    msg = "Color tuple must have 3 (or 4) elements for RGB (or CMYC)."
    assert 3 <= len(tup) <= 4, msg
    msg = "Color tuple must have all elements <= 1.0."
    for i in range(len(tup)):
        assert tup[i] <= 1.0, msg

    if len(tup) == 3:
        colClass = colors.Color
    elif len(tup) == 4:
        colClass = colors.CMYKColor
    return colClass(*tup) 
Example 9
Project: BASS   Author: Cisco-Talos   File: kamino.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _translate_db(db, name = None):
    return {
        "name": name if name is not None else ("random_%s" % "".join(random.choice(string.letters + string.digits) for _ in range(32))),
        "architecture": {
            "type": db.architecture_name,
            "size": {32: "b32", 64: "b64"}[db.architecture_bits],
            "endian": {"little": "le", "big": "be"}[db.architecture_endianness],
        },
        "functions": [{
            "name": func.name,
            "id": func.entry_point,
            "call": func.calls,
            "api": func.apis,
            "sea": func.entry_point,
            "see": max(chunk.end for chunk in func.chunks),
            "blocks": [{
                "id": bb.id,
                "sea": bb.start + (1 if bb.thumb else 0),
                "eea": bb.end,
                "name": bb.name,
                "bytes": "".join("%02x" % ord(x) for x in bb.bytes),
                "dat": dict((hd.address, "".join("%02x" % ord(y) for y in db.get_bytes(hd.data_refs[0], hd.data_refs[0] + 8))) \
                        for hd in bb.code_heads if len(hd.data_refs) >= 1 and db.get_bytes(hd.data_refs[0], hd.data_refs[0] + 8) is not None),
                "src": [("0x%X" % hd.address, hd.disassembly.split()[0]) + tuple(op["opnd"] for op in hd.data["operands"]) \
                        for hd in bb.code_heads if hd.mnemonic != ""],
                "call": [succ.id for succ in bb.successors]} for bb in func.basic_blocks],
        } for func in db.functions],
    } 
Example 10
Project: simple-ga   Author: tmsquill   File: simple-ga.py    License: MIT License 5 votes vote down vote up
def __init__(self, length):

        self.string = ''.join(random.choice(string.letters) for _ in xrange(length))
        self.fitness = -1 
Example 11
Project: simple-ga   Author: tmsquill   File: simple-ga.py    License: MIT License 5 votes vote down vote up
def mutation(agents):

    for agent in agents:

        for idx, param in enumerate(agent.string):

            if random.uniform(0.0, 1.0) <= 0.1:

                agent.string = agent.string[0:idx] + random.choice(string.letters) + agent.string[idx+1:in_str_len]

    return agents 
Example 12
Project: browserscope   Author: elsigh   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def gen_salt():
    salt = ''
    chars = string.letters + string.digits
    
    for i in range(5):
            salt += random.choice(chars)
            
    return salt 
Example 13
Project: browserscope   Author: elsigh   File: xmpp_request_handler.py    License: Apache License 2.0 5 votes vote down vote up
def get_boundary_and_content(self):
    """Returns the message boundary and entire content body for the form."""
    boundary = '----=' + ''.join(random.choice(string.letters + string.digits)
                                 for _ in range(25))
    s = cStringIO.StringIO()

    for name, value, sub_type in self._data:
      s.write('--%s\r\n' % boundary)
      s.write('Content-Type: text/%s; charset="UTF-8"\r\n' % sub_type)
      s.write('Content-Disposition: form-data; name="%s"\r\n' % name)
      s.write('\r\n')
      s.write('%s\r\n' % value.encode('utf-8'))
    s.write('--%s--\r\n' % boundary)
    return boundary, s.getvalue() 
Example 14
Project: bayeslite   Author: probcomp   File: test_loom_backend.py    License: Apache License 2.0 5 votes vote down vote up
def test_loom_guess_schema_nominal():
    """Test to make sure that LoomBackend handles the case where the user
    provides a nominal variable with more than 256 distinct values. In this
    case, Loom automatically specifies the unbounded_nominal type.
    """
    with tempdir('bayeslite-loom') as loom_store_path:
        with bayesdb_open(':memory:') as bdb:
            bayesdb_register_backend(bdb,
                LoomBackend(loom_store_path=loom_store_path))
            bdb.sql_execute('create table t (v)')
            vals_to_insert = []
            for i in xrange(300):
                word = ""
                for _j in xrange(20):
                    letter_index = bdb._prng.weakrandom_uniform(
                        len(string.letters))
                    word += string.letters[letter_index]
                vals_to_insert.append(word)
            for i in xrange(len(vals_to_insert)):
                bdb.sql_execute('''
                    insert into t (v) values (?)
                ''', (vals_to_insert[i],))

            bdb.execute('create population p for t (v nominal)')
            bdb.execute('create generator g for p using loom')
            bdb.execute('initialize 1 model for g')
            bdb.execute('analyze g for 50 iterations')
            bdb.execute('drop models from g')
            bdb.execute('drop generator g')
            bdb.execute('drop population p')
            bdb.execute('drop table t') 
Example 15
Project: sysadmin-tools   Author: jose-delarosa   File: genpasswd.py    License: Apache License 2.0 5 votes vote down vote up
def GenPasswd1(len):
   passwd = ''
   chars = string.letters + string.digits
   for i in range(len):
      passwd = passwd + choice(chars)
   return passwd 
Example 16
def check_prefix(prefix):
    allow_chars = string.letters + string.digits
    if len(prefix) < 3:
        print "[-] The length of 'prefix' must > 3"
        return False
    for i in prefix:
        if i not in allow_chars:
            print "[-] The prefix must be [a-zA-Z0-9]"
            return False
    return True 
Example 17
Project: CVE-2017-7494   Author: joxeankoret   File: mssqlrelayclient.py    License: GNU General Public License v3.0 5 votes vote down vote up
def sendNegotiate(self,negotiateMessage):
        self.init_connection()
        #Also partly copied from tds.py
        login = TDS_LOGIN()

        login['HostName'] = (''.join([random.choice(string.letters) for _ in range(8)])).encode('utf-16le')
        login['AppName']  = (''.join([random.choice(string.letters) for _ in range(8)])).encode('utf-16le')
        login['ServerName'] = self.server.encode('utf-16le')
        login['CltIntName']  = login['AppName']
        login['ClientPID'] = random.randint(0,1024)
        login['PacketSize'] = self.packetSize
        login['OptionFlags2'] = TDS_INIT_LANG_FATAL | TDS_ODBC_ON    
        login['OptionFlags2'] |= TDS_INTEGRATED_SECURITY_ON
        # NTLMSSP Negotiate
        auth = negotiateMessage
        login['SSPI'] = str(auth)

        login['Length'] = len(str(login))

        # Send the NTLMSSP Negotiate
        self.sendTDS(TDS_LOGIN7, str(login))

        # According to the spects, if encryption is not required, we must encrypt just 
        # the first Login packet :-o 
        if self.resp['Encryption'] == TDS_ENCRYPT_OFF:
            self.tlsSocket = None

        tds = self.recvTDS()
        return tds['Data'][3:] 
Example 18
Project: CVE-2017-7494   Author: joxeankoret   File: secretsdump.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 19
Project: CVE-2017-7494   Author: joxeankoret   File: serviceinstall.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 = '' 
Example 20
Project: MegaQC   Author: ewels   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, password=None, **kwargs):
        """
        Create instance.
        """
        db.Model.__init__(self, **kwargs)
        self.salt = getrandstr(rng, digits + letters, 80)
        self.api_token = getrandstr(rng, digits + letters, 80)
        if password:
            self.set_password(password)
        else:
            self.password = None

        if self.user_id == 1:
            self.is_admin = True 
Example 21
Project: MegaQC   Author: ewels   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reset_password(self):
        password = getrandstr(rng, digits + letters, 10)
        self.set_password(password)
        return password 
Example 22
Project: magpie   Author: charlesthomas   File: server.py    License: MIT License 5 votes vote down vote up
def _rand_str(length=64):
    return ''.join([choice(letters + digits) for i in range(0, length)]) 
Example 23
Project: Webshell-Sniper   Author: WangYihang   File: WebShell.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_working(self, url, method, auth):
        Log.info("Checking whether the webshell is still work...")
        flag = random_string(32, string.letters)
        token = random_string(32, string.letters)
        Log.info("Using challenge flag : [%s]" % (flag))
        Log.info("Using token : [%s]" % (token))
        code = "echo '%s'; echo '%s'; echo '%s';" % (token, flag, token)
        result = self.php_code_exec(code)
        if result[0]:
            content = result[1]
            for i in content.split(token):
                if i == flag:
                    return True
        return False
        '''
        method = string.upper(method)
        if method == "POST" or method == "REQUEST":
            Log.info("Using POST method...")
            data = {auth:'echo "'+token+'";echo "'+flag+'";echo "'+token+'";'}
            response = requests.post(url, data=data)
        elif method == "GET":
            Log.info("Using GET method...")
            params = {auth:'echo "'+token+'";echo "'+flag+'";echo "'+token+'";'}
            url = build_url(url, params)
            data = {key:value}
            response = requests.post(url, data=data)
        else:
            Log.error("Unsupported method!")
            return False
        content = response.content
        # Log.success("The content is :\n " + content)
        ''' 
Example 24
Project: Webshell-Sniper   Author: WangYihang   File: WebShell.py    License: GNU General Public License v3.0 5 votes vote down vote up
def php_code_exec_token(self, code):
        token = random_string(32, string.letters)
        code = 'echo "%s";%s;echo "%s";' % (token, code, token)
        result = self.php_code_exec(code)
        if result[0]:
            content = result[1]
            return (True, content.split(token)[1])
        else:
            content = "Time out!"
            return (False, content) 
Example 25
Project: Webshell-Sniper   Author: WangYihang   File: mount.py    License: GNU General Public License v3.0 5 votes vote down vote up
def eval_php_code(code):
    token = random_string(string.letters, 0x10)
    code = "error_reporting(0);echo '%s';%s;echo '%s';die();" % (token, code, token)
    data = {
        param:code,
    }
    response = requests.post(url, data=data)
    result = response.text.split(token)
    if len(result) == 3:
        return result[1]
    return "" 
Example 26
Project: Webshell-Sniper   Author: WangYihang   File: mount.py    License: GNU General Public License v3.0 5 votes vote down vote up
def readdir(self, path, fh):
        token = random_string(string.letters, 0x10)
        code = " \
        echo join(scandir(base64_decode('%s')), '%s'); \
        " % (path.encode("base64").rstrip("\n"), token)
        return list(eval_php_code(code).split(token)) 
Example 27
Project: ironpython2   Author: IronLanguages   File: test_pkgimport.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kw):
        self.package_name = 'PACKAGE_'
        while self.package_name in sys.modules:
            self.package_name += random.choose(string.letters)
        self.module_name = self.package_name + '.foo'
        unittest.TestCase.__init__(self, *args, **kw) 
Example 28
Project: ironpython2   Author: IronLanguages   File: test_pkgimport.py    License: Apache License 2.0 5 votes vote down vote up
def test_package_import__semantics(self):

        # Generate a couple of broken modules to try importing.

        # ...try loading the module when there's a SyntaxError
        self.rewrite_file('for')
        try: __import__(self.module_name)
        except SyntaxError: pass
        else: raise RuntimeError, 'Failed to induce SyntaxError'
        self.assertNotIn(self.module_name, sys.modules)
        self.assertFalse(hasattr(sys.modules[self.package_name], 'foo'))

        # ...make up a variable name that isn't bound in __builtins__
        var = 'a'
        while var in dir(__builtins__):
            var += random.choose(string.letters)

        # ...make a module that just contains that
        self.rewrite_file(var)

        try: __import__(self.module_name)
        except NameError: pass
        else: raise RuntimeError, 'Failed to induce NameError.'

        # ...now  change  the module  so  that  the NameError  doesn't
        # happen
        self.rewrite_file('%s = 1' % var)
        module = __import__(self.module_name).foo
        self.assertEqual(getattr(module, var), 1) 
Example 29
Project: ironpython2   Author: IronLanguages   File: test_dict.py    License: Apache License 2.0 5 votes vote down vote up
def test_literal_constructor(self):
        # check literal constructor for different sized dicts
        # (to exercise the BUILD_MAP oparg).
        for n in (0, 1, 6, 256, 400):
            items = [(''.join(random.sample(string.letters, 8)), i)
                     for i in range(n)]
            random.shuffle(items)
            formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items)
            dictliteral = '{' + ', '.join(formatted_items) + '}'
            self.assertEqual(eval(dictliteral), dict(items)) 
Example 30
Project: ironpython2   Author: IronLanguages   File: test_csv.py    License: Apache License 2.0 5 votes vote down vote up
def test_char_write(self):
        import array, string
        a = array.array('c', string.letters)
        fd, name = tempfile.mkstemp()
        fileobj = os.fdopen(fd, "w+b")
        try:
            writer = csv.writer(fileobj, dialect="excel")
            writer.writerow(a)
            expected = ",".join(a)+"\r\n"
            fileobj.seek(0)
            self.assertEqual(fileobj.read(), expected)
        finally:
            fileobj.close()
            os.unlink(name)