在解析文件时需要一些帮助。我要导入的文件类似于下面的内容。我希望能够搜索此文件中的任何细节“asa,nxos”,以便我可以为每种类型的设备编写命令。现在我正在寻找列出每一行并阅读它的最佳方法。
简而言之,我创建了一个hosts-sticky文件,每个脚本都会搜索该文件来提取主机数据。这些脚本将会出去并收集其他信息或对类似主机进行更改。
-----------------
#Fortigate
10.10.10.4,datacenter-fw-2,dc1,prod,fortigate,fortigate,600d
#CiscoNexus7Ks
10.10.10.5,datacenter-ss-core-2,dc1,prod,cisco,nxos,7018
#CiscoASAFirewalls
10.10.10.1,datacenter-admin-fw-1,dc1,prod,cisco,asa,5580
10.10.10.2,datacenter-fw-2,dc1,prod,cisco,asa,5525
10.10.10.3,datacenter-ops-fw-1,dc1,prod,cisco,asa,5515
-----------------
f = open("/etc/hosts-sticky", "r")
for line in f:
line = f.readline().split()
if line != []:
print line
['#Fortigate']
['10.136.25.74,datacenter-fw-2,dc1,prod,fortigate,fortigate,600d']
['#CiscoNexus7Ks']
['10.65.204.27,datacenter-ss-core-2,dc1.prod,cisco,nxos,7018']
['#CiscoASAFirewalls']
['10.65.204.10,datacenter-admin-fw-1,dc1,prod,cisco,asa,5580']
['10.65.248.10,datacenter-fw-2,dc1,prod,cisco,asa,5525']
['10.65.248.113,datacenter-ops-fw-1,dc1,prod,cisco,asa,5515']
f = open("/etc/hosts-sticky", "r")
for line in f:
line = f.readline().split()
if line != []:
my_hosts = line
if 'asa' in my_hosts:
print my_hosts
我错过了什么?
答案 0 :(得分:0)
这对你有用:
f = open("/etc/hosts-sticky", "r")
myList=[]
for line in f:
myList.append(line)
for item in myList:
if "asa" in item:
print(item.split(',')[0:2])
用于:
-----------------
#Fortigate
10.10.10.4,datacenter-fw-2,dc1,prod,fortigate,fortigate,600d
#CiscoNexus7Ks
10.10.10.5,datacenter-ss-core-2,dc1,prod,cisco,nxos,7018
#CiscoASAFirewalls
10.10.10.1,datacenter-admin-fw-1,dc1,prod,cisco,asa,5580
10.10.10.2,datacenter-fw-2,dc1,prod,cisco,asa,5525
10.10.10.3,datacenter-ops-fw-1,dc1,prod,cisco,asa,5515
-----------------
输出以下内容:
['10.10.10.1', 'datacenter-admin-fw-1']
['10.10.10.2', 'datacenter-fw-2']
['10.10.10.3', 'datacenter-ops-fw-1']