Python string.startswith() Examples

The following are 10 code examples of string.startswith(). 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: helpers.py    From EmPyre with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def strip_python_comments(data):
    """
    Strip block comments, line comments, empty lines, verbose statements,
    and debug statements from a Python source file.
    """
    # TODO: implement pyminifier functionality

    lines = data.split("\n")
    strippedLines = [line for line in lines if ((not line.strip().startswith("#")) and (line.strip() != ''))]
    return "\n".join(strippedLines)


###############################################################
#
# Miscellaneous methods (formatting, sorting, etc.)
#
############################################################### 
Example #2
Source File: mac.py    From aumfor with GNU General Public License v3.0 5 votes vote down vote up
def generate_suggestions(self):
        version_addr = self.obj_vm.profile.get_symbol("_version")

        string = self.obj_vm.read(version_addr, 60)

        if string and string.startswith("Darwin"):
            self._set_profile_metadata(string)
            yield True
        else:
            yield False 
Example #3
Source File: mac.py    From volatility with GNU General Public License v2.0 5 votes vote down vote up
def _get_dtb_m_lion(self):
        tbl = self.obj_vm.profile.sys_map["kernel"]
        config = self.obj_vm.get_config()
        
        if config.SHIFT:
            shift_address = config.SHIFT
        else:
            ver_addr = tbl["_version"][0][0] - 0xffffff8000000000

            scanner = catfishScan(needles = ["Catfish \x00\x00"])
            for catfish_offset in scanner.scan(self.obj_vm):
                tmp_shift_address = catfish_offset - (tbl["_lowGlo"][0][0] % 0xFFFFFF80)
                tmp_ver_addr  = ver_addr + tmp_shift_address 
                
                test_buf = self.obj_vm.zread(tmp_ver_addr, 16)
                if test_buf and test_buf.startswith("Darwin"):
                    shift_address = tmp_shift_address
                    break

        self.obj_vm.profile.shift_address = shift_address

        bootpml4 = (tbl["_BootPML4"][0][0] % 0xFFFFFF80) + shift_address
        boot_pml4_dtb = amd64.AMD64PagedMemory(self.obj_vm, config, dtb = bootpml4)
     
        idlepml4_addr = (tbl['_IdlePML4'][0][0]) + shift_address
        idlepml4_ptr = obj.Object("unsigned int", offset = idlepml4_addr, vm = boot_pml4_dtb)

        return idlepml4_ptr.v() 
Example #4
Source File: mac.py    From volatility with GNU General Public License v2.0 5 votes vote down vote up
def generate_suggestions(self):
        version_addr = self.obj_vm.profile.get_symbol("_version")

        string = self.obj_vm.read(version_addr, 60)

        if string and string.startswith("Darwin"):
            self._set_profile_metadata(string)
            yield True
        else:
            yield False 
Example #5
Source File: types.py    From WatchDBG-IDA with MIT License 5 votes vote down vote up
def fromhex(self, string):
        if string.startswith('0x'):
            string=string[2:]

        hx = binascii.unhexlify(string)
        if len(hx) > self.size:
            hx=hx[:self.size]
        else:
            hx = hx.ljust(self.size, b'\x00')

        self.rawvalue = hx 
Example #6
Source File: smbmap.py    From pentestly with GNU General Public License v3.0 5 votes vote down vote up
def color(string, color='', graphic=''):
    """
    Change text color for the Linux terminal.

    Args:
        string (str): String to colorify
        color (str): Color to colorify the string in the following list:
            black, red, green, yellow, blue, purple, cyan, gr[ae]y
        graphic (str): Graphic to append to the beginning of the line
    """


    if not color:
        if string.startswith("[!] "):
            color = 'red'
        elif string.startswith("[+] "):
            color = 'green'
        elif string.startswith("[*] "):
            color = 'blue'
        else:
            color = 'normal'

    if color not in colors:
        print(colors['red'] + 'Color not found: {}'.format(color) + colors['normal'])
        return

    if color:
        return colors[color] + graphic + string + colors['normal']
    else:
        return string + colors['normal'] 
Example #7
Source File: helpers.py    From EmPyre with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def lhost():
    """
    Return the local IP.

    """

    if os.name != "nt":
        import fcntl
        import struct

        def get_interface_ip(ifname):
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                return socket.inet_ntoa(fcntl.ioctl(
                        s.fileno(),
                        0x8915,  # SIOCGIFADDR
                        struct.pack('256s', ifname[:15])
                    )[20:24])
            except IOError:
                return ""

    ip = ""
    try:
        ip = socket.gethostbyname(socket.gethostname())
    except socket.gaierror:
        pass
    except:
        print "Unexpected error:", sys.exc_info()[0]
        return ip

    if (ip == "" or ip.startswith("127.")) and os.name != "nt":
        interfaces = ["eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0"]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                if ip != "":
                    break
            except:
                print "Unexpected error:", sys.exc_info()[0]
                pass
    return ip 
Example #8
Source File: helpers.py    From EmPyre with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def color(string, color=None):
    """
    Change text color for the Linux terminal.
    """

    attr = []
    # bold
    attr.append('1')

    if color:
        if color.lower() == "red":
            attr.append('31')
        elif color.lower() == "yellow":
            attr.append('33')
        elif color.lower() == "green":
            attr.append('32')
        elif color.lower() == "blue":
            attr.append('34')
        return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

    else:
        if string.startswith("[!]"):
            attr.append('31')
            return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
        elif string.startswith("[+]"):
            attr.append('32')
            return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
        elif string.startswith("[*]"):
            attr.append('34')
            return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
        else:
            return string 
Example #9
Source File: helpers.py    From EmPyre with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def complete_path(text, line, arg=False):
    """
    Helper for tab-completion of file paths.
    """
    # stolen from dataq at
    #   http://stackoverflow.com/questions/16826172/filename-tab-completion-in-cmd-cmd-of-python

    if arg:
        # if we have "command something path"
        argData = line.split()[1:]
    else:
        # if we have "command path"
        argData = line.split()[0:]

    if not argData or len(argData) == 1:
        completions = os.listdir('./')
    else:
        dir, part, base = argData[-1].rpartition('/')
        if part == '':
            dir = './'
        elif dir == '':
            dir = '/'

        completions = []
        for f in os.listdir(dir):
            if f.startswith(base):
                if os.path.isfile(os.path.join(dir, f)):
                    completions.append(f)
                else:
                    completions.append(f+'/')

    return completions 
Example #10
Source File: types.py    From WatchDBG-IDA with MIT License 4 votes vote down vote up
def parseType(typestr):
    if not isinstance(typestr, str):
        return None
    typestr = typestr.lower()

    for k,v in typeconverttable.items():
        type = typestr.replace(k,v)

    spstr = typestr.split()
    if len(spstr) > 1:
        childtype = parseType(' '.join(spstr[:-1]))
        if childtype == None:
            return None
        try:
            count = int(spstr[-1])
        except ValueError:
            return None
        
        return WArray(count, childtype)


    if typestr == "raw":
        return WType()
    if typestr == "ptr" or typestr == "pointer":
        return WPtr()
    if typestr == "char":
        return WChar()
    if typestr == "str" or typestr == "string":
        return WString()
    if typestr == "float":
        return WFloat()
    if typestr == "double":
        return WDouble()

    signed = True
    if typestr.startswith("uint"):
        typestr = typestr[1:]
        signed = False
    if typestr.startswith("int"):
        if len(typestr) == 3:
            return WInt(4, signed)
        try:
            size = int(typestr[3:])
        except ValueError:
            return None
        
        return WInt(size//8, signed)
    return None