【问题标题】:about grep "-i" option in for statment关于 for 语句中的 grep "-i" 选项
【发布时间】:2021-07-28 19:43:19
【问题描述】:
import os
f1 = open("/home/ace/Desktop/MB/shell_search/direct.txt",'r',encoding='UTF-8')
lines = f1.readlines()
lines = [line.strip() for line in lines]

for shell in lines:
 os.system("cat IIS_W3C_Log.log | grep -i \"" + shell + "\" > "+shell+".txt")

-i 选项不起作用...您的代码有问题? 区分大小写字母。

如果在“shell”中遇到特殊字符(符号),代码会抛出错误。即使出现符号,如何防止错误发生?

【问题讨论】:

  • 您将文件名搜索到文件本身?
  • 顺便说一句,grep 期望给出一个正则表达式作为要评估的表达式。如果direct.txt 不包含正则表达式,您可能需要类似grep -F 的东西。
  • @foreaser,更好的minimal reproducible example 将解释破坏您的代码的特定示例输入的示例。如果问题是由字符串 -bash 引起的,与由字符串 foo[bar 引起的问题是非常不同的(例如,第一个用 grep 的 -e 参数修复,后一个用-F 参数,因为它们会导致两个完全不同的失败......并且这些失败都与 -i 没有任何关系。
  • 我学到了一些新东西。我还是个初学者,还有很多东西要学。谢谢。

标签: python linux grep kali-linux


【解决方案1】:

os.system() 启动一个 shell。如果您的direct.txt 包含$(rm -rf ~),则该shell 将删除您的主目录。

不要这样做,尤其是在根本没有理由使用 shell 的情况下。

更好的代码会在原生 Python 中进行字符串搜索;但如果我们出于某种原因想要继续使用grep,可能看起来像:

import subprocess

f1 = open("/home/ace/Desktop/MB/shell_search/direct.txt", 'r', encoding='UTF-8')

for line in f1:
    shell = line.strip()
    shell_safe = shell.replace('/', '_').lstrip('.')
    if shell_safe == '':
        print("Skipping unsafe pattern: %q" % shell, file=sys.stderr)
        continue
    subprocess.call(
        ['grep', '-i', '-e', shell],
        stdin=open('IIS_W3C_Log.log', 'r'),
        stdout=open(f'{shell_safe}.txt', 'w')
    )

【讨论】:

  • @foreaser,...顺便说一句,我回去对这个答案做了一些改进。它现在使用更少的内存,因为它不再将文件中的所有行加载到内存中并在运行第一个 grep 之前对其进行处理,而是在运行时读取它们;而且它更安全,因为像../../../../../../etc/passwd 这样的字符串不能用于覆盖您正在工作的目录之外的文件。(当然,该示例会写入/etc/passwd.txt 之类的东西,但即使覆盖.txt 文件也有可能滥用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多