首页 > 解决方案 > 创建一个python脚本并使用grep命令?

问题描述

我正在创建一个脚本,其中我想根据列表 grep 所有特定地址?

在我通常使用此命令 ex 运行 grep 1 by 1 之前。grep "192.168.1.1" *

现在我正在创建一个脚本。

输出示例。

print(i) output.
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3

但是如何调用列表并在 os.system 下放入循环以便我可以 grep 所有列表?

谢谢

import ipaddress
import os

#Ask the ipaddress in CIDR format
ip = input("Enter the IP/CIDR: ")

os.chdir("/rs/configs")
print("pwd=%s" % os.getcwd())

for i in ipaddress.IPv4Network(ip):
    print (i)
    os.system("grep $i '*') #<--Grep from list and run to all directory *

标签: pythonpython-3.xpython-2.7

解决方案


基本答案是"grep {} '*'".format(ip),但您的脚本存在许多问题。

为了提高可用性,我建议您更改脚本,以便它接受 IP 地址列表作为命令行参数。

你想避免os.system()赞成subprocess.run()

不需要到cd包含您要检查的文件的目录。

最后,真的不需要 run grep,因为 Python 本身非常有能力搜索一组文件。

import ipaddress
import glob

ips = set([ipaddress.IPv4Network(ip) for ip in sys.argv[1:]])

for file in glob.glob('/rs/configs/*'): 
    with open(file) as lines:
        for line in lines:
            if any(x in line for x in ips):
                print("{0}:{1}".format(file, line))

通过只检查一次文件,这应该会显着提高效率。

ipaddress如果您无论如何都在寻找单个 IP 地址,那么您希望通过使用这里获得什么并不完全清楚。


推荐阅读