2011-01-11 16 views
0

私はログファイルから必要な情報を抽出するために正規表現(import re)を試しています。複数行チェックの正規表現

更新:すべてのサンプルコードを破ったC:\WINDOWS\securityフォルダのアクセス許可が追加されました。

C:\: 
    BUILTIN\Administrators Allowed: Full Control 
    NT AUTHORITY\SYSTEM Allowed: Full Control 
    BUILTIN\Users Allowed: Read & Execute 
    BUILTIN\Users Allowed: Special Permissions: 
      Create Folders 
    BUILTIN\Users Allowed: Special Permissions: 
      Create Files 
    \Everyone Allowed: Read & Execute 
    (No auditing) 

C:\WINDOWS\system32: 
    BUILTIN\Users Allowed: Read & Execute 
    BUILTIN\Power Users Allowed: Modify 
    BUILTIN\Power Users Allowed: Special Permissions: 
      Delete 
    BUILTIN\Administrators Allowed: Full Control 
    NT AUTHORITY\SYSTEM Allowed: Full Control 
    (No auditing) 

C:\WINDOWS\system32\config: 
    BUILTIN\Users Allowed: Read & Execute 
    BUILTIN\Power Users Allowed: Read & Execute 
    BUILTIN\Administrators Allowed: Full Control 
    NT AUTHORITY\SYSTEM Allowed: Full Control 
    (No auditing) 

C:\WINDOWS\security: 
    BUILTIN\Users Allowed: Special Permissions: 
      Traverse Folder 
      Read Attributes 
      Read Permissions 
    BUILTIN\Power Users Allowed: Special Permissions: 
      Traverse Folder 
      Read Attributes 
      Read Permissions 
    BUILTIN\Administrators Allowed: Full Control 
    NT AUTHORITY\SYSTEM Allowed: Full Control 
    (No auditing) 

そして、それはいくつかの他のディレクトリのために繰り返される:

は、ログの形式があると言います。 paragraphsに分割してSpecial Permissions:が含まれている行を確認するにはどうすればよいですか?このよう

:いくつかの部分に

  1. セパレート全体がstring1、C:\C:\WINDOWS\system32
  2. 表示行全体、例えば:次の '段落'

私のため C:\: BUILTIN\Users Allowed: Special Permissions: \n\ Create Folders\n\ BUILTIN\Users Allowed: Special Permissions: \n\ Create Files\n\

  • リピート: '特殊なアクセス権' を含む各ラインで
  • ルック考えていた: 1.全体のテキストファイルを検索するr"(\w+:\\)(\w+\\?)*:" - 私にパスを返す Special Permissions 4.ディスプレイを持つもの以外の他のすべての行を削除し、ステップ1

    を繰り返し出力 3の残りの部分を取得する2. String関数や正規表現しかし、私は、それは効率的ではないと思います。

    誰もが私にこれを案内できますか?ありがとう。


    出力例:行には特別な許可がありませんよう

    C:\: 
    BUILTIN\Users Allowed: Special Permissions: 
    Create Folders 
    BUILTIN\Users Allowed: Special Permissions: 
    Create Files 
    
    C:\WINDOWS\system32: 
    BUILTIN\Power Users Allowed: Special Permissions: 
    Delete 
    
    C:\WINDOWS\security: 
    BUILTIN\Users Allowed: Special Permissions: 
    Traverse Folder 
    Read Attributes 
    Read Permissions 
    BUILTIN\Power Users Allowed: Special Permissions: 
    Traverse Folder 
    Read Attributes 
    Read Permissions 
    

    C:\WINDOWS\system32\configは表示されません。


    私が使用していますテンプレート:

    import re 
    
    text = "" 
    
    def main(): 
        f = open('DirectoryPermissions.xls', 'r') 
        global text 
        for line in f: 
         text = text + line 
        f.close 
        print text 
    
    def regex(): 
        global text 
        <insert code here> 
    
    if __name__ == '__main__': 
        main() 
        regex() 
    

  • +0

    は 're'モジュールではなく、' regex'を使用してください。また、三重引用符で囲まれた文字列を調べます。 – nmichaels

    +3

    最後にどのようなデータが必要ですか? – MattH

    +0

    @nmichaels、Lol編集します。私は 'import re'を使用しています @MattH - 各パスに' Special Permissions: 'を含む完全な行を表示するには –

    答えて

    0

    milkypostmanのおかげでここ

    data = '''\ 
    C:\: 
        BUILTIN\Administrators Allowed: Full Control 
        NT AUTHORITY\SYSTEM Allowed: Full Control 
        BUILTIN\Users Allowed: Read & Execute 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Folders 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Files 
        \Everyone Allowed: Read & Execute 
        (No auditing) 
    
    C:\WINDOWS\system32: 
        BUILTIN\Users Allowed: Read & Execute 
        BUILTIN\Power Users Allowed: Modify 
        BUILTIN\Power Users Allowed: Special Permissions: 
          Delete 
        BUILTIN\Administrators Allowed: Full Control 
        NT AUTHORITY\SYSTEM Allowed: Full Control 
        (No auditing) 
    
    C:\WINDOWS\system32\config: 
        BUILTIN\Users Allowed: Read & Execute 
        BUILTIN\Power Users Allowed: Read & Execute 
        BUILTIN\Administrators Allowed: Full Control 
        NT AUTHORITY\SYSTEM Allowed: Full Control 
        (No auditing) 
    ''' 
    
    if __name__ == '__main__': 
        import re 
    
        # A regular expression to match a section "C:...." 
        cre_par = re.compile(r''' 
           ^C:.*? 
           ^\s*$''', re.DOTALL | re.MULTILINE | re.VERBOSE) 
    
        # A regular expression to match a "Special Permissions" line, and the 
        # following line. 
        cre_permissions = re.compile(r'''(^.*Special\ Permissions:\s*\n.*)\n''', 
               re.MULTILINE | re.VERBOSE) 
    
        # Create list of strings to output. 
        out = [] 
        for t in cre_par.findall(data): 
         out += [t[:t.find('\n')]] + cre_permissions.findall(data) + [''] 
    
        # Join output list of strings together using end-of-line character 
        print '\n'.join(out) 
    

    は、生成された出力であります残りはソリューションを思いついた:

    def regex(): 
        global text 
        for paragraph in text.split('\n\n'): 
         lines = paragraph.split('\n', 1) 
         #personal modifier to choose certain output only 
         if lines[0].startswith('C:\\:') or lines[0].startswith('C:\\WINDOWS\system32:') or lines[0].startswith('C:\\WINDOWS\\security:'): 
          print lines[0] 
          iterables = re.finditer(r".*Special Permissions: \n(\s+[a-zA-Z ]+\n)*", lines[1]) 
          for items in iterables: 
           #cosmetic fix 
           parsedText = re.sub(r"\n$", "", items.group(0)) 
           parsedText = re.sub(r"^\s+", "", parsedText) 
           parsedText = re.sub(r"\n\s+", "\n", parsedText) 
           print parsedText 
          print 
    

    私はまだ投稿されたコード(esp。私が決して純粋な弦の操作はそれほど強力でないことを知らなかったので、嘲笑します)。洞察に感謝します!

    もちろん、これは最適ではありませんが、私の場合はうまくいきます。何か提案があれば、気軽に投稿してください。


    出力:

    C:\Python27>openfile.py 
    C:\: 
    BUILTIN\Users Allowed:  Special Permissions: 
    Create Folders 
    BUILTIN\Users Allowed:  Special Permissions: 
    Create Files 
    
    C:\WINDOWS\security: 
    BUILTIN\Users Allowed:  Special Permissions: 
    Traverse Folder 
    Read Attributes 
    Read Permissions 
    BUILTIN\Power Users  Allowed:  Special Permissions: 
    Traverse Folder 
    Read Attributes 
    Read Permissions 
    
    C:\WINDOWS\system32: 
    BUILTIN\Power Users  Allowed:  Special Permissions: 
    Delete 
    
    2
    # I would replace this with reading lines from a file, 
    # rather than splitting a big string containing the file. 
    
    section = None 
    inspecialperm = False 
    with open("testdata.txt") as w: 
        for line in w: 
         if not line.startswith("   "): 
          inspecialperm = False 
    
         if section is None: 
          section = line 
    
         elif len(line) == 0: 
          section = None 
    
         elif 'Special Permissions' in line: 
          if section: 
           print section 
           section = "" 
          inspecialperm = True 
          print line, 
    
         elif inspecialperm: 
          print line, 
    
    +0

    こんにちは、ありがとうございます、今仕事中です。 =) –

    +0

    私はあなたのコードを試しましたが、部分的に動作し、それらの特別な権限を正しく選択していますが、権限自体を表示しません。私はそれを耳にしてみよう。 –

    +0

    少し更新しました。 「特別な権限」行がなく、権限を表示する必要がある場合は、セクションヘッダを印刷しません。タブを印刷したくない場合は、印刷する前にタブを印刷してください。 – milkypostman

    1

    をあなたはもっとある "スプリット&ストリップ" による文字列を解析している場合は、すべてのreモジュールを必要としません。効率:

    for paragraph in string1.split('\n\n'): 
        path = paragraph.split('\n', 1)[0].strip().rstrip(':') 
        paragraph = paragraph.replace(': \n', ': ') # hack to have permissions in same line 
        for line in paragraph.split('\n'): 
         if 'Special Permissions: ' in line: 
          permission = line.rsplit(':', 1)[-1].strip() 
          print 'Path "%s" has special permission "%s"' % (path, permission) 
    

    print声明はあなたのニーズに合っています。

    EDIT:としては、コメントで指摘し、以前のソリューションは、編集された問題で、新たな入力行では動作しませんが、ここでは(まだ、より効率的に正規表現を使用するよりも)それを修正する方法は次のとおりです。

    for paragraph in string1.split('\n\n'): 
        path = paragraph.split('\n', 1)[0].strip().rstrip(':') 
        owner = None 
        for line in paragraph.split('\n'): 
         if owner is not None and ':' not in line: 
          permission = line.rsplit(':', 1)[-1].strip() 
          print 'Owner "%s" has special permission "%s" on path "%s"' % (owner, permission, path) 
         else: 
          owner = line.split(' Allowed:', 1)[0].strip() if line.endswith('Special Permissions: ') else None 
    
    +0

    こんにちは、ありがとうございます。 =) –

    +0

    あなたのコードでは、何とかして提示したときに壊れる:C:\ WINDOWS \セキュリティ:\t可 \t BUILTIN \ユーザー:\t特別権限: \t \t \tフォルダのスキャン \t \t \t読むには \t \t \tアクセス許可の読み取り –

    +0

    がTrueの属性。質問を編集する前に元の入力文字列を解析することを意図していました。今度は最後のケースに合わせてソリューションを更新しました。興味深い。 – scoffey

    0

    ここでは、reモジュールとfindallメソッドを使用するソリューションがあります。 milkypostmanのソリューションと同様に

    C:\: 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Folders 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Files 
        BUILTIN\Power Users Allowed: Special Permissions: 
          Delete 
    
    C:\WINDOWS\system32: 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Folders 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Files 
        BUILTIN\Power Users Allowed: Special Permissions: 
          Delete 
    
    C:\WINDOWS\system32\config: 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Folders 
        BUILTIN\Users Allowed: Special Permissions: 
          Create Files 
        BUILTIN\Power Users Allowed: Special Permissions: 
          Delete 
    
    +0

    こんにちは、ありがとうコードが、出力が間違っています。 'system32 \ config'は現れてはいけません。' system32'には 'Special Permissions:Delete'しかありません。 'C:\:'には 'ファイルとフォルダの作成 'のみが必要です。それにもかかわらず、私は後であなたのコードを調べます。ありがとうございました –

    1

    、しかし形式であなたがその出力を持つようにしようとしている:scoffey

    lines=string1.splitlines() 
    seperator = None 
    for index, line in enumerate(lines): 
        if line == "": 
         seperator = line 
        elif "Special Permissions" in line: 
         if seperator != None: 
          print seperator 
         print line.lstrip() 
         offset=0 
         while True: 
          #if the line's last 2 characters are ": " 
          if lines[index+offset][-2:]==": ": 
           print lines[index+offset+1].lstrip() 
           offset+=1 
          else: 
           break 
    
    +0

    こんにちは、私はこのコードを試してみましたが、私はそれを動作させることができない、それは "フォルダの作成"を印刷し、それを手動で終了する必要があります。何が悪かったのか? –

    +0

    私の間違い。ごめんなさい。今修正されました。 –

    +0

    あなたのロジックは他のものとは違ってコード化されています。とにかく、あなたは特別なアクセス許可を正しく取得してみるといいですが、それぞれのディレクトリを表示しません。 –