2016-04-05 15 views
2

PythonでのRegexのマッチングに関する本当に混乱している問題に対処しています。 は、私はそのようなregex101などのデバッグツールでは正常に動作し、正規表現パターンのペアを持っている:Python regex groupdictは、グループの文字列の代わりに単一の文字を返します。

しかし、イム一度スクリプトで実装されている場合、開始見積もりの​​前にrのようにコンパイルされていない限り、パターンは一致しません。

それでも一致すると、グループdictの1文字が返されます。

私がここで間違っていることについて誰でも指針を提供できますか?

deobf.py:

#!/bin/python 
import sys 
import getopt 
import re 
import base64 

#################################################################################### 
# 
# Setting up global vars and functions 
# 
#################################################################################### 

# Assemble Pattern Dictionary 
pattern={} 
pattern["HexOct"]=re.compile(r'([\"\'])(?P<obf_code>(\\[xX012]?[\dA-Fa-f]{2})*)\1') 
pattern["Base64"]=re.compile(r'([\"\'])(?P<obf_code>[\dA-Za-z\/\+]{15,}={0,2})\1') 

# Assemble more precise Pattern handling: 
sub_pattern={} 
sub_pattern["HexOct"]=re.compile(r'((?P<Hex>\\[xX][\dA-Fa-f]{2})|(?P<Oct>\\[012]?[\d]{2}))') 

#print pattern # trying to Debug Pattern Dicts 
#print sub_pattern # trying to Debug Pattern Dicts 

# Global Var init 
file_in="" 
file_out="" 
code_string="" 
format_code = False 

# Prints the Help screen 
def usage(): 
    print "How to use deobf.py:" 
    print "-----------------------------------------------------------\n" 
    print "$ python deobf.py -i {inputfile.php} [-o {outputfile.txt}]\n" 
    print "Other options include:" 
    print "-----------------------------------------------------------" 
    print "-f : Format - Format the output code with indentations" 
    print "-h : Help - Prints this info\n" 
    print "-----------------------------------------------------------" 
    print "You can also use the long forms:" 
    print "-i : --in" 
    print "-o : --out" 
    print "-f : --format" 
    print "-h : --Help" 

# Combination wrapper for the above two functions 
def deHexOct(obf_code): 
    match = re.search(sub_pattern["HexOct"],obf_code) 
    if match: 

     # Find and process Hex obfuscated elements 
     for HexObj in match.groupdict()["Hex"]: 
      print match.groupdict()["Hex"] 
      print "Processing:" 
      print HexObj.pattern 
      obf_code.replace(HexObj,chr(int(HexObj),16)) 

     # Find and process Oct obfuscated elements 
     for OctObj in set(match.groupdict()["Oct"]): 
      print "Processing:" 
      print OctObj 
      obf_code.replace(OctObj,chr(int(OctObj),8)) 
    return obf_code 

# Crunch the Data 
def deObfuscate(file_string): 
    # Identify HexOct sections and process 
    match = re.search(pattern["HexOct"],file_string) 
    if match: 
     print "HexOct Obfuscation found." 
     for HexOctObj in match.groupdict()["obf_code"]: 
      print "Processing:" 
      print HexOctObj 
      file_string.replace(HexOctObj,deHexOct(HexOctObj)) 

    # Identify B64 sections and process 
    match = re.search(pattern["Base64"],file_string) 
    if match: 
     print "Base64 Obfuscation found." 
     for B64Obj in match.groupdict()["obf_code"]: 
      print "Processing:" 
      print B64Obj 
      file_string.replace(B64Obj,base64.b64decode(B64Obj)) 

    # Return the (hopefully) deobfuscated string 
    return file_string 

# File to String 
def loadFile(file_path): 
    try: 
     file_data = open(file_path) 
     file_string = file_data.read() 
     file_data.close() 
     return file_string 
    except ValueError,TypeError: 
     print "[ERROR] Problem loading the File: " + file_path 

# String to File 
def saveFile(file_path,file_string): 
    try: 
     file_data = open(file_path,'w') 
     file_data.write(file_string) 
     file_data.close() 
    except ValueError,TypeError: 
     print "[ERROR] Problem saving the File: " + file_path 

#################################################################################### 
# 
# Main body of Script 
# 
#################################################################################### 
# Getting the args 
try: 
    opts, args = getopt.getopt(sys.argv[1:], "hi:o:f", ["help","in","out","format"]) 
except getopt.GetoptError: 
    usage() 
    sys.exit(2) 

# Handling the args 
for opt, arg in opts: 
    if opt in ("-h", "--help"): 
     usage() 
     sys.exit() 
    elif opt in ("-i", "--in"): 
     file_in = arg 
     print "Designated input file: "+file_in 
    elif opt in ("-o", "--out"): 
     file_out = arg 
     print "Designated output file: "+file_out 
    elif opt in ("-f", "--format"): 
     format_code = True 
     print "Code Formatting mode enabled" 

# Checking the input 
if file_in =="": 
    print "[ERROR] - No Input File Specified" 
    usage() 
    sys.exit(2) 

# Checking or assigning the output 
if file_out == "": 
    file_out = file_in+"-deObfuscated.txt" 
    print "[INFO] - No Output File Specified - Automatically assigned: "+file_out 

# Zhu Li, Do the Thing! 
code_string=loadFile(file_in) 
deObf_String=deObfuscate(str(code_string)) 
saveFile(file_out,deObf_String) 
次のように私のデバッグプリントから

。コンソール出力は次のようになります。

C:\Users\NJB\workspace\python\deObf>deobf.py -i "Form 5138.php" 
Designated input file: Form 5138.php 
[INFO] - No Output File Specified - Automatically assigned: Form 5138.php-deObfuscated.txt 
HexOct Obfuscation found. 
Processing: 
\ 
Processing: 
x 
Processing: 
6 
Processing: 
1 
Processing: 
\ 
Processing: 
1 
Processing: 
5 
Processing: 
6 
Processing: 
\ 
Processing: 
x 
Processing: 
7 
Processing: 
5 
Processing: 
\ 
Processing: 
1 
Processing: 
5 
Processing: 
6 
Processing: 
\ 
Processing: 
x 
Processing: 
6 
Processing: 
1 

答えて

1

あなたの正規表現がうまくマッチするグループですが、その後、文字を反復処理しています一致したグループで文字列内の文字を超えるmatch.groupdict()["Hex"]

この繰り返し処理:

for HexObj in match.groupdict()["Hex"]: 

あなたが検索を繰り返すので、re.finditer()の代わりre.search()を使用する代わりにしたい

この

はあなただけでマッチした文字列を与えます。だから、のようなもの:

def deHexOct(obf_code): 
    for match in re.finditer(sub_pattern["HexOct"],obf_code): 
     # Find and process Hex obfuscated elements 
     groups = match.groupdict() 
     hex = groups["Hex"] 
     if hex: 
      print "hex:", hex 
      # do processing here 
     oct = groups["Oct"] 
     if oct: 
      print "oct:", oct 
      # do processing here 

はまた、文字列の前にrはちょうどエスケープとしてPython解釈バックスラッシュを停止し、彼らはまた、エスケープのためにバックスラッシュを使用しているため、正規表現のために必要とされています。代わりに正規表現内のすべてのバックスラッシュを2倍にすることもできます。 rというプレフィックスは必要ありませんが、正規表現は読みにくくなる可能性があります。

+0

残念ながら、文字の問題を指摘してくれてありがとう、返された一致オブジェクトにはgroupdict()メソッドがないことを示すfindallのエラーが出ます。興味深いことに、それを印刷することは、それが鍵なしのdictであることを明らかにする。私はfinditer()ともう少し運があったが、まだ不器用です。 – Minothor

+1

申し訳ありませんが、 'finditer'と言っていたはずです。 'finditer'はマッチオブジェクトを返します、' findall'は文字列を返します。 – Duncan

+0

その変更により、私は機能性を持っています!今私はDRYestの可能な解決策に自分の仕事を削減する必要があります。 – Minothor

関連する問題