创建一个python脚本,并使用grep命令?

问题描述 投票:-1回答:1

我创建一个脚本,其中我希望到grep根据列表中的所有具体地址?

之前,我通常用1使用此命令前运行的grep 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 *
python python-3.x python-2.7
1个回答
0
投票

最基本的答案是"grep {} '*'".format(ip)但也有许多与你的脚本的问题。

为了提高易用性,我建议你改变了脚本,以便它接受作为命令行参数,而不是IP地址的列表。

你要避免有利于os.system()subprocess.run()

有没有必要cd到包含您要检查的文件的目录。

最后,没有必要真的跑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这里如果你是无论如何grepping单个IP地址获得什么。

© www.soinside.com 2019 - 2024. All rights reserved.