Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建python脚本并使用grep命令?_Python_Python 3.x_Python 2.7 - Fatal编程技术网

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

创建python脚本并使用grep命令?,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我正在创建一个脚本,在此脚本中,我希望根据列表对所有特定地址进行grep 在我通常使用以下命令运行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

我正在创建一个脚本,在此脚本中,我希望根据列表对所有特定地址进行grep

在我通常使用以下命令运行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 *
导入IP地址
导入操作系统
#以CIDR格式询问IP地址
ip=输入(“输入ip/CIDR:”)
os.chdir(“/rs/configs”)
打印(“pwd=%s”%os.getcwd()
对于ipaddress.IPV4网络(ip)中的i:
印刷品(一)
os.system(“grep$i'*')#基本答案是
“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))
通过只检查一次文件,这将大大提高效率


现在还不完全清楚,如果您仍要在此处搜索单个IP地址,那么使用
ipaddress
您希望获得什么。

谢谢,但我已经尝试使用此代码,并且它现在正在工作。回溯(最近一次调用):文件“vr3.py”“,第12行,第322行,用于第行:文件“/usr/lib/python3.7/codecs.py”,在解码(结果,消耗)=self.\u buffer\u解码(数据,self.errors,final)UnicodeDecodeError:“utf-8”编解码器无法解码第7094位的字节0x96:无效的起始字节。如果文件使用一些随机编码,则需要单独指定它。明智的方法是对所有文本数据使用UTF-8。或者这些不是文本文件?作为一种快速而肮脏的解决方法,请尝试
open(file,encoding='cp1252')
,但要理解盲目地假设随机编码确实是一个bug。无论如何,我认为grep在这种情况下也不能可靠地工作。