我有Nmap的扫描报告。我正在尝试获取仅与特定IP地址有关的信息。我正在尝试为该部分代码提取IP地址,稍后将在下一部分中使用。我认为这与\n
IP地址末尾的字符有关。我需要代码说我只想要这个IP地址和这个IP地址。任何帮助是极大的赞赏。
#Python3.X
target_ip = "10.10.100.1"
fhand = open('ScanTest.txt','r')
for line in fhand:
line = line.rstrip()
if line.startswith('Nmap scan report for')and (target_ip):
print(line)
我的结果最终是
Nmap scan report for 10.10.100.1
Nmap scan report for 10.10.100.2
Nmap scan report for 10.10.100.100
Nmap scan report for 10.10.100.101
Nmap scan report for 10.10.100.103
Nmap scan report for 10.10.100.102
您的代码匹配太多,因为总是有一个非空的字符串True
,因此您的代码打印了所有以"Nmap..."
。
之后如何正确编写测试and
?您使用了string方法startswith
,但也有endswith
...
我还自由地将请求的常量移出循环,
target_ip = "10.10.100.1"
begins = "Nmap scan report for"
fhand = open('ScanTest.txt','r')
for line in fhand:
line = line.rstrip()
if line.startswith(begins) and line.endswith(target_ip):
print(line)
从您发布的输出来看,startswith
和endswith
暗示该行完全等于"Nmap scan report for 10.10.100.1
“ ...”。
这可能是更有趣算多少固定线路都出现在文件中(接踵而来的是地道的Python来计算匹配的数量,它的工作原理,因为不匹配的算术值0
和匹配的是1
)
count = sum(line==target_line for line in fhand)
或者在文件中也有位置很有趣
count = 0
for n, line in enumerate(fhand):
if line==target_line:
print("%8d %s"%(n, line))
count = count+1
print(n, "matches found.")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句