Python string.letters() Examples

The following are 30 code examples of string.letters(). 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 also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: WebShell.py    From Webshell-Sniper with 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 #2
Source File: validators.py    From daf-recipes with 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 #3
Source File: irc.py    From Safejumper-for-Desktop with 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 #4
Source File: cmd_runner.py    From avocado-vt with 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
Source File: para.py    From Fluid-Designer with 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 #6
Source File: ms08-067_check.py    From sparta with 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 #7
Source File: helpers.py    From featherduster with 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 #8
Source File: secretsdump.py    From CVE-2017-7494 with 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 #9
Source File: datagen.py    From script-languages with MIT License 5 votes vote down vote up
def get_string(len = None):
    if len == None:
        len = random.randint(0, 1024)
    chars = string.letters + string.digits
    return ''.join(random.choice(chars) for i in range(len)) 
Example #10
Source File: test_string.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example #11
Source File: __init__.py    From HDHRViewerV2.bundle with MIT License 5 votes vote down vote up
def makeSafeFilename(inputFilename):
    try:
        safechars = string.letters + string.digits + "-_."
        return filter(lambda c: c in safechars, inputFilename)
    except:
        return ""

###################################################################################################
# Check if resource exist
################################################################################################### 
Example #12
Source File: 0010.py    From My-Solutions-For-Show-Me-the-Code with Mozilla Public License 2.0 5 votes vote down vote up
def get_letters():
    i = ''
    for loop in range(4):
        i += random.choice(string.letters)
    return i.decode('utf-8') 
Example #13
Source File: rand.py    From tplmap with GNU General Public License v3.0 5 votes vote down vote up
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'] 
Example #14
Source File: androconf.py    From AndroBugs_Framework with GNU General Public License v3.0 5 votes vote down vote up
def random_string():
    return random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) 
Example #15
Source File: util.py    From aamo with MIT License 5 votes vote down vote up
def get_random(mixed_type, str_len):  # Get a random string of strLen lenght
    type_random = string.letters  # Mixedcase Letter
    if not mixed_type:
        type_random = string.lowercase  # Lowercase letter
    return ''.join(random.sample(type_random, str_len)) 
Example #16
Source File: ProxyServiceUtil.py    From p2ptv-pi with MIT License 5 votes vote down vote up
def generate_proxy_challenge():
    chars = string.letters + string.digits
    challenge = ''
    for i in range(8):
        challenge = challenge + random.choice(chars)

    return challenge 
Example #17
Source File: 0010.py    From My-Solutions-For-Show-Me-the-Code with Mozilla Public License 2.0 5 votes vote down vote up
def main():
    letters = get_letters()
    draw_pic(letters) 
Example #18
Source File: secretsdump.py    From cracke-dit with MIT License 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
Source File: test_csv.py    From oss-ftp with MIT License 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) 
Example #20
Source File: test_dict.py    From oss-ftp with MIT License 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 #21
Source File: test_pkgimport.py    From oss-ftp with MIT License 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 #22
Source File: test_pkgimport.py    From oss-ftp with MIT License 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 #23
Source File: test_string.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example #24
Source File: test_csv.py    From BinderFilter with MIT License 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) 
Example #25
Source File: test_pkgimport.py    From BinderFilter with MIT License 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 #26
Source File: test_pkgimport.py    From BinderFilter with MIT License 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 #27
Source File: test_dbshelve.py    From BinderFilter with MIT License 5 votes vote down vote up
def populateDB(self, d):
        for x in string.letters:
            d[self.mk('S' + x)] = 10 * x           # add a string
            d[self.mk('I' + x)] = ord(x)           # add an integer
            d[self.mk('L' + x)] = [x] * 10         # add a list

            inst = DataClass()            # add an instance
            inst.S = 10 * x
            inst.I = ord(x)
            inst.L = [x] * 10
            d[self.mk('O' + x)] = inst


    # overridable in derived classes to affect how the shelf is created/opened 
Example #28
Source File: test_get_none.py    From BinderFilter with MIT License 5 votes vote down vote up
def test02_get_raises_exception(self):
        d = db.DB()
        d.open(self.filename, db.DB_BTREE, db.DB_CREATE)
        d.set_get_returns_none(0)

        for x in string.letters:
            d.put(x, x * 40)

        self.assertRaises(db.DBNotFoundError, d.get, 'bad key')
        self.assertRaises(KeyError, d.get, 'bad key')

        data = d.get(string.letters[0])
        self.assertEqual(data, string.letters[0]*40)

        count = 0
        exceptionHappened = 0
        c = d.cursor()
        rec = c.first()
        while rec:
            count = count + 1
            try:
                rec = c.next()
            except db.DBNotFoundError:  # end of the records
                exceptionHappened = 1
                break

        self.assertNotEqual(rec, None)
        self.assertTrue(exceptionHappened)
        self.assertEqual(count, len(string.letters))

        c.close()
        d.close()

#---------------------------------------------------------------------- 
Example #29
Source File: test_get_none.py    From BinderFilter with MIT License 5 votes vote down vote up
def test01_get_returns_none(self):
        d = db.DB()
        d.open(self.filename, db.DB_BTREE, db.DB_CREATE)
        d.set_get_returns_none(1)

        for x in string.letters:
            d.put(x, x * 40)

        data = d.get('bad key')
        self.assertEqual(data, None)

        data = d.get(string.letters[0])
        self.assertEqual(data, string.letters[0]*40)

        count = 0
        c = d.cursor()
        rec = c.first()
        while rec:
            count = count + 1
            rec = c.next()

        self.assertEqual(rec, None)
        self.assertEqual(count, len(string.letters))

        c.close()
        d.close() 
Example #30
Source File: check_encode.py    From shorty with MIT License 5 votes vote down vote up
def random_token(size = 6):
	"""
	Generates a random string of 6 chars , use size argument 
	to change the size of token.
	Returns a valid token of desired size , 
	*default is 6 chars
	"""
	BASE_LIST = string.digits + string.letters
	
	token = ''.join((random.choice(BASE_LIST)) for char in range(size))
	return token