python - 创建一个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 *
解决方案
基本答案是"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 地址,那么您希望通过使用这里获得什么并不完全清楚。
推荐阅读
- benchmarking - 如何在堆栈的 package.yaml 中指定每个基准参数?
- django - 如果导入未设置为全局,Django shell 上的 Python 脚本看不到导入?
- php - 处理注册请求的路由返回 404
- c++ - 指针和类,输出
- c++ - 带有模板的结构和函数
- c# - 如何断言已将扩展名更改为 csv 的 exe 文件实际上是 csv 文件 c#
- python - 如何从whatsapp web 上抓取数据
- javascript - 如何从 JS 浏览器客户端使不可流式传输的 mp4 流式传输?
- r - R - 评估存储在 data.table 列中的函数
- ios - 表达式类型“()”是模棱两可的,没有更多上下文试图为滚动视图指定大小