def convert(text): mphPattern = r"\d+\.?\d*\smph" floatPattern = r"\d+\.?\d*" match = re.finall(mphPattern, text) for item in match: value = re.finall(floatPattern, item) kmValue = float(value[0]) * 1.60934 kmph = format(kmValue, ".1f") + "km/h" text = text.replace(item, kmph) return text
def get(): global a hd = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36' } url = 'http://www.budejie.com/vedio/' + str(a) html = requests.get(url, headers=hd).content.decode('utf-8') #发送get请求 print(html) url_content = re.compile(r'(<div class="j-r-list-c">.*?</div>.*?</div>)', re.S) #编译,提高效率 url_contents = re.findall(url_content, html) print(url_contents) for i in url_contents: url_reg = r'data-mp4="(.*?)">' url_items = re.finall(url_reg, i) #print(url_items) if url_items: #如有有视频存在,我就匹配名字,如果是图片或文字就不匹配 name_reg = re.compile(r'<a href="/detail-.{8}?.html">(.*?)</a>') name_items = re.findall(name_reg, i) #print(name_items) for i, k in zip(name_items, url_items): url_name.append([i, k]) #print(i,k) return url_name
def block_to_list(args): re_roles = re.finall(r"dd.[a-zA-Z]*.*dd", args) upgraded_list = [] for role in re_roles: upgraded_list.append(re_roles[role][2:-3]) return upgraded_list
def findLetters(sentences): l = [] ex = r'@\d{1,2} ?(?:am|pm)' for sentence in sentences: words =re.finall(ex, sentence) for word in words: l.append(word1:]) return l
def get_url_list( a_list): #only works for chinarun.com, get the list of chinarun event content = list() for i in a_list: tmp = re.finall('href="(.*)" target', i) url = tag('www.chinarun.com/html', tmp, "") content.append(url) return url
def sqli(host): global sess_admin data = {"section_name": "asd?"} r = sess_admin.post('http://%s/index.php/section/add' % host, data=data) flags = re.finall(r'~(.+?)~', r.content) if flags: return flags[0] else: return "error pwn!"
def CheckDpkgStatus(): """ uses dpkg-query shell command to check if code is installed at all, and to check if the dpkg status is 'installed OK' or 'half-installed' """ command = 'dpkg-query' flag = '--status' package = 'code' ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE) output = subprocess.check_output((command, flag, package), stdin=ps.stdout) ps.wait() output = output.decode('utf-8') patternHalfInstalled = r'\bStatus: install reinstreq half-installed\b' patternOk = r'\bStatus: install ok installed\b' ok = 'Status: install ok installed' if output is not None: # ---------------------------------------- # search for ok # ---------------------------------------- try: result = re.findall(patternOk, output) except AttributeError: result = None matchValue = "" if result: for item in result: matchValue = item if matchValue == "Status: install ok installed": print(col.LT_GREEN + 'Microsoft Visual Studio Code installed with status:\n' + col.LT_BLUE + ok + col.NC) # ---------------------------------------- # search for half-installed # ---------------------------------------- try: result = re.finall(patternHalfInstalled, output) except AttributeError: result = None if result: for item in result: matchValue = item if matchValue == ok: command = 'sudo dpkg --force-remove-reinstreq --remove code' subprocess.call(command, shell=True) print( col.LT_BLUE + 'Partially installed package removed, VSCode uninstalled.') print('Re-run this script to re-install.' + col.NC) else: print(col.YELLOW + 'Code is not installed.' + col.NC)
def th(ur): base = "http://finance.yahoo.com/q?s="+ur regex = '<span id="yfs_l84_'+ur.lower()+'">(.+?)</span>' pattern = re.compile(regex) htmltext = urllib.urlopen(base).read() results = re.findall(pattern,htmltext) gmap[ur] = re.finall(pattern,htmltext) try: gmap[ur] = results[0] except: print "got an error"
def strings_command(ff): list_of_files = glob.glob('./*') latest_file = str(max(list_of_files, key=os.path.getctime)).replace('./', '') starting_click() click.echo(' Searching for Possible Flags..') temp_image = open(latest_file) temp_lines = temp_image.readlines() new_ff = ff.replace('HELLO}', '') image_command = 'strings {} | grep {}'.format(latest_file, new_ff) flag_p = os.popen(image_command).read() flag_p = re.finall(r'{}'.foramat(ff)) result_click() click.echo(' Potential Flag found: {}'.format(flag_p)) pyperclip.copy(flag_p) return flag_p
def get_words(self, http_response): # splits out the header from the message body headers, body = http_response.tostring().split('\r\n\r\n', 1) # skip the non-text responses if headers.lower().find('content-type: text') == -1: return # TagStripper class strips the HTML code from the rest of the page text tag_stripper = TagStripper() page_text = tag_stripper.strip(body) # regular expression; find all words starting with an alphabetic character # followed by 2 or more 'word' characters words = re.finall('[a-zA-Z]\w{2,}', page_text) for word in words: # filter out long strings if len(word) <= 12: # successful words are saved in lowercase to the wordlist self.wordlist.add(word.lower()) return
import math import re from collections import defaultdict def tokenize(message); message = message.lower() all_words = re.finall("[a-z0-9']+", message) return set(all_words) def count_words(training_set): """ Training set consist of pairs (message, is_spam) """ counts = defaultdict(lambda: [0,0]) for message, is_spam in training_set: for word in tokenize(message): counts[word][0 if is_spam else 1] += 1 return counts def word_probabilities(counts, total_spams, total_non_spams, k=0.5): """ Turn word_counts into a list of triplets:(w, p(w|spam), and p(w|~spam)) """ return [(w, (spam + k) / (total_spams + 2 * k), (non_spam + k) / (total_non_spams + 2 * k)) for w, (spam, non_spam) in counts.iteritems()] def spam_probability(word_probs, message): message_words = tokenize(message) log_prob_if_spam = log_prob_if_not_spam = 0.0
def find_flag(ff): re.finall(r'picoCTF{.*?}')
import re filename = input("ENTER THE C FILE:") searchfile = open(filename,"r") vulnc = ['gets','strcpy','stpcpy','strcat','strcmp','sprintf'] gets = re.findall('gets(',searchfile) strcpy = re.finall('strcpy(',searchfile) stpcpy = re.finall('stpcpy(',searchfile) strcat = re.finall('strcat(',searchfile) strcmp = re.finall('strcmp(',searchfile) sprintf = re.finall('sprintf(',searchfile) if len(gets) != 0: print(""" MITIGATION: USE FGETS INSTEAD GETS """ ) else: pass if len(strcpy) != 0: print(""" MITIGATION: USE STRLCPY INSTEAD OF STRCPY """ ) else: pass if len(stpcpy) != 0: print(""" MITIGATION: USE STRLPY INSTEAD OF STPCPY """
# difference between group() and group() import re str = 'ab' m = re.match('ab', str) print m.group() # 'ab' print m.groups() # None m = re.match('(a)(b)', str) print m.group() # 'ab' print m.groups() # ('a','b') m = re.search('(a)(b)', str) print m.group() # 'ab' print m.group() # ('a','b') m = re.finall('(a)(b)', str) print m # [('a','b')]
def addLink(switch_ip, megabytes): switch_ip = "192.168.57.200" switch_pw = "cisco" port_in = "GigabitEthernet 0/1" port_out = "GigabitEthernet 0/28" ports = [port_in, port_out] #vlan_id = 100 verbose = True # subnet = "192.168.57." suffix = str(2) megabytes = 25 # megabytes demanded bits = megabytes * 8 * 1000000 # what percent of 125 is the request # ports are GigabitEthernet, so max bandwithd is 125. request = int(float(megabytes) // 125 * 100) try: try: child = pexpect.spawn('telnet %s' % (switch_ip)) if verbose: child.logfile = sys.stdout child.timeout = 4 child.expect('Password:'******'t log on to the switch") child.sendline(switch_pw) child.expect('>') child.sendline('terminal length 0') child.expect('>') child.sendline('enable') child.expect('Password:'******'#') child.sendline('configure terminal') child.expect('\(config\)#') # Create a vlan # try: # child.sendline('int vlan %d', vlan_id) # o = child.expect(['\(config-if\)#', '% Invalid']) # if o != 0: # raise Exception("invalid vlan number '%s', must be 1 - 4094." % (port)) # child.sendline("ip address " + subnet + suffix) # o = child.expect(['\(config-if\)#', '% Invalid']) # if o != 0: # raise Exception("Error addressing vlan") # child.sendline("no shut") # child.expect('\(config-if\)#') # child.sendline("end") # child.expect('\(config\)#') # # try: # # child.sendline("rate-lime input {} {} {} conform-action transmit exceed-action drop".format(bits, bits/2000, bits/2000)) # # child.expect('\(config-if\)#') # # child.sendline("rate-lime output {} {} {} conform-action transmit exceed-action drop".format(bits, bits/2000, bits/2000)) # # child.expect('\(config-if\)#') # # child.sendline("end") # # child.expect('\(config\)#') # # except: # # raise Exception("Error assigning bitrate on vlan") # except: # raise Exception("Error creating vlan.") # Allowing Vlan on interface for p in ports: child.sendline( "show mls qos interface {} queueing | include bandwidth". format(p)) rate_description = child.readline() rate = re.finall("\d+", rate_description)[0] child.expect('\(config\)#') child.sendline('interface %s' % (p)) o = child.expect(['\(config-if\)#', '% Invalid']) if o != 0: raise Exception("Unknown switch port '%s'" % (port)) # child.sendline('switchport access vlan %s' % (vlan_id)) child.expect('\(config-if\)#') child.sendline('no shutdown') child.expect('\(config-if\)#') try: new_rate = rate + request assert new_rate <= 100 if new_rate > 90: child.sendline('no srr-queue bandwidth limit') child.expect('\(config-if\)#') elif new_rate >= 10: child.sendline( 'srr-queue bandwidth limit {}'.format(new_rate)) child.expect('\(config-if\)#') else: raise Exception( "Error encoutered allocating bandwidth on port {}". format(p)) except AssertionError: raise Exception("requested bandwidth not available") child.sendline( "show mls qos interface {} queueing | include bandwidth". format(p)) child.sendline('wr mem') child.expect('[OK]') child.expect('#') child.sendline('quit') except (pexpect.EOF, pexpect.TIMEOUT), e: raise error("Error while trying to increase bandwidth on switch.")
else: sum2 += mod2 * 2 x //= 10 # retrieve input x = str(copy) checksum = str(sum1 + sum2) if re.findall("0$", checksum): if le == 15: if re.findall("^34", x) or re.findall("^37", x): print("AMEX") else: print("INVAL6D") elif le == 13: if re.finall("^4", x): print("VISA") else: print("INVAL5D") elif le == 16: if re.findall("^4", x): print("VISA") elif re.findall("^51|52|53|54|55", x): # ^51|52|53|54|55 works # ^51|52|53|54|55 won't work print("MASTERCARD") else: print("INVALID") else: print("INVALID") else:
def getContent(self, page): page = self.getPage(1) pattern = re.compile('<div id="post_content_.*?>(.*?)</div>', re.S) items = re.finall(pattern, page) for item in items: print item
return _compile(pattern, flags).search(string) File "D:\Python\lib\re.py", line 286, in _compile p = sre_compile.compile(pattern, flags) File "D:\Python\lib\sre_compile.py", line 764, in compile p = sre_parse.parse(p, flags) File "D:\Python\lib\sre_parse.py", line 930, in parse p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0) File "D:\Python\lib\sre_parse.py", line 426, in _parse_sub not nested and not items)) File "D:\Python\lib\sre_parse.py", line 532, in _parse source.tell() - here) re.error: unterminated character set at position 0 >>> re.search(r'[\n]','FishCFish.C\n') <re.Match object; span=(11, 12), match='\n'> >>> >>> re.finall(r'[^a-z]','Fish') Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> re.finall(r'[^a-z]','Fish') AttributeError: module 're' has no attribute 'finall' >>> >>> re.search(r'FishC{3}','FishCCC') <re.Match object; span=(0, 7), match='FishCCC'> >>> # 匹配C三次 >>> >>> re.search(r'FishC{3}','FishCFishCFishC') >>> re.search(r'(FishC){3}','FishCFishCFishC') <re.Match object; span=(0, 15), match='FishCFishCFishC'> >>> # 想要整体匹配加上小括号 >>> >>> re.search(r'(FishC){24}','FishCFishCFishC')
# FiveDollarTenCents / memehk.py # by Kobura.Nephilim # version 2.0 # Tested on raspberry pi # # This python program will get the page from memehk, # extract the youtube id of the live stream and # pass the youtube id to livestreamer to record into mp4 import urllib2 import re memehk_url='http://www.memehk.com/index.php?page=live&channel=1' req = urllib2.Request(url=memehk_url) resp = urllib2.urlopen(req) text = resp.read() youtubeid = re.finall('(?<=embed\/).{11}', text) print youtubeid[1]