Python 3.X 在尝试读取文件时拉取太多 IP 地址



我有一份来自Nmap的扫描报告。我正在尝试获取仅与特定 IP 地址有关的信息。我正在尝试为这部分代码提取 IP 地址,稍后我将处理下一部分。我认为这与IP地址末尾的n字符有关。我需要代码说我想要这个 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后如何正确编写测试?您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)

从您发布的输出来看,startswithendswith暗示该行正好等于"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.")

我认为您需要更改行...

if line.startswith('Nmap scan report for')and (target_ip):

。自。。。

if line.startswith('Nmap scan report for') and (line.split(' ')[4] == target_ip):

相关内容

最新更新